_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
0 | How to move my character by itself but I can still move its direction or where it is going, using Mobile Joystick? So, I am making a 2D airplane game right now and I wanted to know how to move my player automatically but I can still control where it should go or the direction. How do I code this using Mobile joystick? CODE public float moveSpeed Rigidbody2D myBody protected Joystick joystick void Start() myBody GetComponent lt Rigidbody2D gt () joystick FindObjectOfType lt Joystick gt () Update is called once per frame void Update() myBody.velocity new Vector2( joystick.Horizontal moveSpeed, joystick.Vertical moveSpeed ) |
0 | Convert the animation inside FBX into Unity Recently i bought a package with an fbx and lots of animations. Since I want full control and change a couple of details, I want to convert them into the regular Unities Animation System. I cant convert them into the normal Unity Animations though. They are "read only". I can load them, copy paste them into my own "not read only" animation file. But somehow i cant change the file anymore after I pasted something inside. What am I doing wrong? Is that something "impossible"? Can you guys help? |
0 | Make objects stack in unity? I have two kinematic rigidbody cubes from the standard 3D objects, I have also enabled contact pairs mode to quot all contact pairs quot , how do I make it so that no matter what angle they collide in they perserve the same angle but just get out of each others space making it look like they're in contact e.g. collided? Here is my attempt at doing that using System.Collections using System.Collections.Generic using UnityEngine public class Physics MonoBehaviour private Collider collider1 private bool grounded false used to determine if the collider hit something so it doesnt keep going down Start is called before the first frame update void Start() collider1 GetComponent lt Collider gt () Update is called once per frame void Update() if (!grounded) if the collider hit something, stop going down collider1.transform.Translate(0f, .1f,0f,Space.World) private void OnCollisionEnter(Collision collision) grounded true the collider hit something if(collider1.transform.position.y ! collider1.bounds.extents.y) if this is true, it means it is at the floor so dont move it transform.position new Vector3(collider1.transform.position.x, collision.collider.bounds.size.y collider1.bounds.extents.y, collider1.transform.position.z) attempts to put the collider on top of whatever it get This works if the cubes are right on top of each other with no angle It also works if one of the cubes collides at a angle to the other cube, when they collide the bottom cube perverse its angle of collision and and the top cube just gets out of the space of the other collider making it look like they have collided What doesn't seem to work is if both cubes collide with each other at a angle, although they preserve their angle of collision, and also get out of each others space, they do not remain in contact with each other which if they did would make it look like they have collided. Instead there is a gap between them, how do I get rid of the gap e.g. make it so that no matter what angle the objects are at they get out of each others space, preserve the angle, and remain in contact with each other to give the illusion that they have collided? |
0 | How to implement the seek steering behavior in Unity3d? Following this tutorial Understanding Steering Behaviors Seek, I tried to add seek and steering behavior to my Unity prototype but it's not working this is my script. The cube does not steer it just follows the target. public GameObject target float maxForce 15 float maxSpeed 30 float maxVelocity 200 float mass 15 Vector3 velocity void Start() velocity Vector3.zero void Update() transform.LookAt(target.transform) var desiredVelocity target.transform.position transform.position desiredVelocity desiredVelocity.normalized maxVelocity Time.deltaTime var steering desiredVelocity velocity steering Vector3.ClampMagnitude(steering, maxForce) steering steering mass velocity Vector3.ClampMagnitude(velocity steering, maxSpeed) transform.position velocity Time.deltaTime What could be the problem?? |
0 | How to refer to a object that has just been hit by a ray cast? I would like to use RigidbodyConstraints.FreezeRotation in order to freeze the rotation of an object that is picked up. The problem is I don't know how to refer (or call) the currently selected object. The script in it's currents state is below... public class PhysGun MonoBehaviour private GameObject Player void Start () Player GameObject.Find("Player") Update is called once per frame void Update () Vector3 fwd transform.forward Equivalent to the code you had. Ray ray new Ray(transform.position, transform.forward) RaycastHit hit if (Input.GetMouseButton(0) amp amp Physics.Raycast(ray, out hit, 10f)) hit.transform.SetParent(Player.transform) Debug.Log("We hit " hit.transform.name) hit.transform. RigidbodyConstraints.FreezeRotation So, how do I call (or refer to) the object that is hit by the ray cast exactly? |
0 | Manipulating an animation towards a target object (ie. The hand and arm lean towards the target) I am trying to make a boxing game just for fun (I dont expect the end product to be anything decent lol) . I have my boxers in the ring and they are animated quite well so far, with Idle, and punch Left and Right. They also rotate so they are always looking at each other. What I want to do is give the punch some aim towards the head. I will give the punch a set amount which it can move from the standard animation and move the hand bone in the direction of the targets head object. But I don't know how to do this S So far i have used dragged the 3 animation files into Mecanim and coded it to do the animations when a button is pressed. Is there a way to manipulate the animation in this way? (ie. actually make the arm reach towards the target object ) |
0 | Unity look at rotation on one axis only problem Hey I would like an object to look at another object only at one axis, when I rotate the white cube all around the gray cube (gray has look at script), the gray cube flips as soon as the target passes the middle and is on the right side. How can I fix this, so that rotation is normal. Below is when the cube (target, white). Below is what happens when the cube (target) passes on the other side, as you can see by the texture the gray cube flips horizontally. Below is how it should be (texture shows difference) Code Quaternion lookAngle Quaternion.LookRotation(targetPos, Vector3.up) Thanks in advance! |
0 | Ocean visible through the island's lake in Unity3D? I'm working on a puzzle game featuring islands there is a plane with a water shader, and objects colliding with that plane. Now I'd like to make lakes on the islands, with different (higher) water levels than the ocean's. The problem is that if I put a water plane in a "hole", I can see the ocean below at best, or even worse, the upper water surface just glitches out and disappear. One option is that I move the lake's basin higher than the ocean's see level. This works, but I it doesn't look so good, because the lake becomes too shallow. Another option is that I cut holes in the ocean's plane, but that seems a bit overengineered, isn't it? Is there a better solution? Also having a water plane for every "lake tile" causes some problems but I want to have dynamic lakes, so having a 2x2 water plane for a 2x2 group of lake tiles isn't a walkable path. |
0 | Character controller passes through mesh collider I need a little help figuring out what's going on with an NPC's character controller. Here are the character controller settings for the NPC. The problem I'm running into is that the NPC isn't walking up a slight gradient as it should instead, it moves through the ground. Below are the settings for the ground. The NPC isn't on the ground it is a few units off. Any help is greatly appreciated. Thanks in advance... |
0 | Best way make static GameObject clickable 2D I've built a turn based battle combat game (like pokemon) but i'm stuck between a rock and a hard place. Asfar as i understod UI elements should be inside Canvas, while Players, Enemies, Items and etc... Should not be inside a canvas. Correct me if i'm wrong. I've tried different ways how to handle this situation. Such as make Enemy as a button, but seems not to fire. Since i think it has to be inside a canvas. Also make enemy which have animations as button, may not be a good idea? Update event, to check if the mouse is down and mouse position is converted with screentoworldpoint and see if the positions matches with the enemy position. Update event, to check if the mouse is down and rayCast see if we colide with something. But i dont feel like this is neccesary since the enemy does not move. So the position is always the same. Also if it's possible to take into consideration that every enemy is different size. But this is a minor detail, i would like firstly tackle the best way handle onClick event without the extra overhead. I would appericate any feedback on my dilemma. |
0 | One rock gameobject drops FPS heavily! Okay so this is really odd I have a game object (a rock) that even though is really high detail drops my fps from around 70 steady to 12! Now the object is divided into LOD's and the closer I get to the object the worse it gets! I have created a Material for each LOD of the object where i replace the normal map with a lower LOD (The other channels stay the same). The import settings for the different LODS looks like this Now as of the textures they are set to 2k (all of them) Can anyone tell me why this is happening? The object itself looks like this inside the game Even my scene view has framerate issues when looking at it. |
0 | Use arrow keys to navigate between specific toggles, not all UI elements I'm making a game where the player needs to select a object out of three and navigates between then with the arrows of the keyboard, and I'm using toggles to make this system. But the problem is that when I hit play, the navigation mixes the toggles with some other UI elements I dont want to include in the navigation, like sliders and buttons. How can I lock the navigation for just these three toggles? I also want to make the navigation switch between these toggles and another three toggles in the middle of the game. How would I change my navigation via script? |
0 | Unity how to set Off mesh link speed How can I set agent's speed on off mesh link? I want it to look like a jump, but now it looks like it was in slow motion. |
0 | Raycast Masks not working Unity3D I'm having a problem with filters masks when raycasting. I've created a LayerMask and then in the inspector selected the layer I want to ignore when Raycasting. however then I print out the name of the object hit by the raycast I am still getting hits on objects on the layer masked out, as well as on other layers. public LayerMask rayMask RaycastHit hit Ray ray Camera.main.ScreenPointToRay(Input.mousePosition) if (Physics.Raycast (ray, out hit,rayMask)) Debug.Log (hit.collider.name) I have paused the Game and checked that the object I'm getting a hit on is indeed on the layer in the mask. |
0 | For creating a distant moon in a 3D game, is it better to use a model or texture? I'm working on my indie game and I want to create a moon (it's a 3D game) however I am unsure if I should create a model and put it far away, or if I should use a texture on a plane and have it constantly move so the face of the plane is facing the player. The problem I had last time I tried a model is the render view, as the model was really far away (as when I did it very small, you could sort of tell it was a tiny model rather then a far away moon) and with the texture I'm not sure if it comes across as tacky. I'd really like to hear the pros and cons of each, since I'm planning to use the 'render objects only when in view' method and basically want advice on which I should go with. |
0 | Prefabs moved to before position when zooming scene I have build some pipes for waterline drawing, like following screencast https youtu.be WnJb1JwOW78 As you can see, when I zoom in the scene, Pipes moved to lower position. When i zoom out, Pipes moved to higher position. Actually I have changed the position and moved down the pipe position before, the unexpected higher position was the pipe before position. So i guessing this problem might about cache clean. So I I try to clear the GI cache, but the problem still exist. And then I try to build a windows executable file and run game again, problem still. How to fix it? I am using Unity 2018.4 |
0 | How can I efficiently make a solid Texture2D? I am trying to programmatically make an Image to cover the entire screen. I create the Texture2D, then create a Sprite from the Texture2D, then apply the Sprite to my Image. This works, but it is slow. I suspect the issue is that I am setting each pixel individually for my Texture2D private static Texture2D CreateSolidTexture2D(Color color) var texture new Texture2D(Screen.width, Screen.height) for (int y 0 y lt texture.height y ) for (int x 0 x lt texture.width x ) texture.SetPixel(x, y, color) texture.Apply() return texture I have tried creating the Texture2D by resizing a Texture2D of a single pixel, but the color comes out as a translucent white, instead of the color passed private static Texture2D CreateSolidTexture2D(Color color) var texture new Texture2D(1, 1) texture.SetPixel(0, 0, color) texture.Resize(Screen.width, Screen.height) texture.Apply() return texture Why doesn't my second approach work? How can I efficiently create a screen sized Texture2D of a solid color? |
0 | Unity3d zooming with orthogonal camera like in Google maps I am implementing 2d orthogonal zoom. As far as I know in Unity3d there are no translations like in OpenGL. Taking this into consideration, I work with camera size camera position (center) real world mouse position I have no issues implementing simple zoom in zoom out operations, combined with camera position changes ( drag'n'drop ) But I have some issues calculating camera zoom shift in this case camera size (4,4) camera position (0,0) real world mouse position (1,0) A double zoom in (2x) is applied, as a result camera size (2,2) camera position (0.5,0) real world mouse position (1,0) User shifts real mouse position to (1.5,0) and applies a double zoom out ( 0.5 ). In this case camera size is again (4,4) camera position ??????? real world mouse position (1.5,0) What should be the camera shift so the mouse doesn't visually move ? What is the formula for calculation in this case ? Thank you in advance. P.S. Any suggestion regarding current method of handling zoom are welcome Update So I resolved this issue with Blue's help. The basic idea about shifting is right. The main reason it didn't work was incorrect zoom factor. Example Initial camera size is 5. User zooms in by 1, camera size is now 4 ( it displays less content on the same 'screen'). User changes mouse position and zooms out by 1. Camera size is 5 again, but the amount of zoom is actually different initially the change was 20 ( 1 5 ) in the second time, the change was 25 ( 1 4 ) My fault was that, when zooming out, I tried to restore position by 20 , not 25 . |
0 | How can i check when Lerp has finished? private bool hitted false private Vector3 hitPosition private void Test() RaycastHit hit if (Physics.Raycast(start.position, Vector3.left, out hit, 1.5f) Physics.Raycast(start.position, Vector3.right, out hit, 1.5f) Physics.Raycast(start.position, Vector3.forward, out hit, 1.5f)) if (hit.transform.tag "Test") hitted true hitPosition hit.transform.localPosition private void Update() if (hitted true) player.localRotation Quaternion.Lerp(player.localRotation, Quaternion.LookRotation(hitPosition), 1 Time.deltaTime) What i want to detect is when the player finished rotating and then set back hitted to false. |
0 | Can I integrate Unity 5 with the 0.6.0 runtime for Oculus DK2? I am a new user and I am trying to get the Oculus running on an old PC. I had a few issues with the latest SDK so I am currently using the 0.6.0.1 beta version. I would like to integrate Oculus with Unity. My question is whether I can use Unity 5 with the SDK 0.6.0.1 beta and which kind of integration should I use or if I should download a previous release of Unity. Thank you! |
0 | GameObject transform with respect to local camera? I'd like to recycle objects as they pass behind the camera frustum i.e, the plane of the local Z axis, orthogonal to the camera vector Camera.main.transform.forward. Is there a nice method to test for the above case? That is, "if a GameObject's location lt local Z 0 plane", we can know that it is behind the camera. |
0 | Unity animation transition with 0 Exit Time doesn't transition immediately Question Why doesn't an animation transition with an Exit Time of 0 immediately transition to the next state? Minimal example Using Unity 2018.3, I set up an AnimatorController with two states Initial and Next. I wanted Initial to transition to Next immediately, so I tried setting an Exit Time of 0. However, this doesn't transition immediately As shown above, Initial state still runs instead of transitioning immediately to the Next state. (There is no Motion attached to the AnimationState, so perhaps it's using a default duration.) Below are screenshots of my animation transition settings. Strange behaviour with small non zero ExitTime I also tried using an Exit Time of 0.01 (i.e. transition after 1 of the animation has played), and it transitions almost immediately as I expect most of the time. However, occasionally it will still play the Initial state In this case, even though it transitions to Next immediately most of the time, it still occasionally waits for the Initial state to complete. (It happens much less frequently than the image above suggests, but the issue becomes more frequent if I set the ExitTime even lower, e.g. 0.003). Workaround From searching online, the recommended solution for immediate animation transitions seems to be to turn off Exit Time and use a condition (e.g. bool or trigger) to transition immediately instead. (Edit in my case, I've defined an animator bool parameter called ImmediateTransition and set it to true by default instead of using Exit Time 0.) This seems to work, but I would like to better understand how Exit Time works and why it's not working the way I expect. |
0 | Align spawned particle system I am working on a game in which tanks can shoot at each other. I intend to spawn a spark particle system (particles emit to Z) when a bullet hits a surface. I want to align the Z axis of the newly spawned particle system to be a) in a 90 degree angle to surface that has been hit b) in a reflective angle from the original trajectory I know that I can "fake it" by setting particle Z to World 90 degrees, however then it will do so on any angled surface, while I would like to have the particle system dynamically orient itself in a 90 degree angle away from the surface that has been hit or reflect into the direction away from the incoming bullet. hope you can help me, getting quite frustrated. |
0 | What is the most appropriate way to achieve synchronous Addressable asset loading? I am transitioning my project from Resources to Addressables. Some parts of my game just aren't worth doing asynchronously, and would just cause more problems but I still want to use Addressables for its other benefits. Anyway, it doesn't offer any synchronous methods in their API. Unity has an official repository with an example for "synchronous addressables" right here https github.com Unity Technologies Addressables Sample blob master Advanced Sync 20Addressables Assets SyncAddressables SyncAddressables.cs Although the code does appear to work in the few tests I've done The code below won't always work, and it doesn't make sense to me anyway. This is the relevant method public static TObject LoadAsset lt TObject gt (object key) if(!s Initialized) throw new Exception("Whoa there friend! We haven't init'd yet!") var op Addressables.LoadAssetAsync lt TObject gt (key) if(!op.IsDone) throw new Exception("Sync LoadAsset failed to load in a sync way! " key) if (op.Result null) var message "Sync LoadAsset has null result " key if (op.OperationException ! null) message " Exception " op.OperationException throw new Exception(message) return op.Result It will throw an exception if the asset didn't manage to load instantly (the !op.isDone part). Sure, that's technically synchronous, but it seems to ignore the elephant in the room if the asset is large I would expect it to need a bit more time (i.e. freeze the game), which is fine for my current needs but instead, the game will just end up crashing because it couldn't load immediately. What is the most appropriate way to achieve synchronous Addressable asset loading? |
0 | How can I change the rotatearound radius in real time when the game is running? using System.Collections using System.Collections.Generic using UnityEngine public class TargetBehaviour MonoBehaviour Add this script to Cube(2) Header("Add your turret") public GameObject Turret to get the position in worldspace to which this gameObject will rotate around. Header("The axis by which it will rotate around") public Vector3 axis by which axis it will rotate. x,y or z. Header("Angle covered per update") public float angle or the speed of rotation. public float upperLimit, lowerLimit, delay upperLimit amp lowerLimit heighest amp lowest height private float height, prevHeight, time height height it is trying to reach(randomly generated) prevHeight stores last value of height delay in radomness Range(0, 50) public float xradius 5 Range(0, 50) public float yradius 5 private void Start() Update is called once per frame void Update() Gets the position of your 'Turret' and rotates this gameObject around it by the 'axis' provided at speed 'angle' in degrees per update transform.RotateAround(Turret.transform.position, axis.normalized, angle) time Time.deltaTime Sets value of 'height' randomly within 'upperLimit' amp 'lowerLimit' after delay if (time gt delay) prevHeight height height Random.Range(lowerLimit, upperLimit) time 0 Mathf.Lerp changes height from 'prevHeight' to 'height' gradually (smooth transition) transform.position new Vector3(transform.position.x, Mathf.Lerp(prevHeight, height, time), transform.position.z) Using the xradius and yradius sliders I want to change the transform.RotateAround radius in real time. UPDATE I added this to the Update if (radius gt 0) var newPos (transform.position Turret.transform.position).normalized radius newPos Turret.transform.position transform.position newPos The problem is now that some times when the radius the distance from the Turret is small for example 20 or less some times the transform is getting right above the turret not sure why. I want it to rotate around the turret at the fixed set distance(radius) but not to be above the turret. Can't figure out why sometimes it's moving right above the turret then after some time it's getting back to the set distance. |
0 | Resize sprite to match camera width? I'm trying to resize my small background sprite to match the screen width of the user's device. This is what I'm trying Use this for initialization void Start () Set filterMode SpriteRenderer sr (SpriteRenderer) GetComponent("Renderer") sr.sprite.texture.filterMode FilterMode.Point Get scaling float multiplier Camera.main.rect.width sr.sprite.bounds.size.x Scale transform.localScale localScale multiplier It seems there is a problem with the measure I get from the Camera width, I also tried Screen.width but it seems it returns the value in pixels. |
0 | Animating 2d character which can wear items? In my game the player can control a character which can wear items. Now it is not visible but I would like to make it visible like for example in Terraria, Starbound, etc. In my game a player can only face right or left. (right is the mirrored version of left) Only the character's feet and arms are moving during the game. Is there a simple way in Unity to stick the sprite of the items to "bones"? (like in 3d modelling) Or how could I implement this "equipment on character" system? I found some assets but I dont have much money. Thanks in advance! ) |
0 | Physics.CheckSphere never returning true despite being called to where a hitbox is I'm trying to create a random level generator where I have a load of rooms 16x10 and I generate them when the player enters the room. I want to check the space where I want to place a room, in this case up for if there's already a room there. I've written this code to do that but it doesn't appear to be working. Currently it should ALWAYS return true (and not run the code) because the object it is on has a hitbox. I want it to hit triggers because then I don't need a physical block in the centre of every room (hard when the rooms are even both ways) Can you see what's wrong here? The code does spawn a block in the correct place. if (!Physics.CheckSphere(new Vector2(transform.position.x, transform.position.y), 1f, 6, QueryTriggerInteraction.Collide)) Get list of open bottoms getList("Assets Room Lists bottom.txt") Make a random number from the list int newRoomIndex random.Next(0, prefabObjects.Count) Get that object GameObject newRoom prefabObjects newRoomIndex Place it in the world in the correct position Instantiate(newRoom, new Vector3(transform.position.x 8, transform.position.y 15, transform.position.z), Quaternion.identity) |
0 | How to edit key value pairs (like a Dictionary) in Unity's inspector? I have a spell system I am creating, the principle is as follows Each spell is an autonomous prefab. It contains a script with some properties (base damage, duration...) that can be modified in the inspector. I have a Spell enum listing all possible spells in the code, which is used in the game logic When I want to cast a spell, I need to be able to get this spell's prefab to instantiate it and read its informations Each actor (be it players or enemies) needs to have a list of possible animations for the spells The problems with how I am trying to implement are For listing each actor's animations I could use a Dictionary lt Spell, Animation gt , but dictionaries aren't supported by the inspector which makes it hard to easily edit multiple actors type. I need some way to easily access a spell prefab from the corresponding enum. Here too I could use a dictionary but I can only reference to prefabs in the inspector, not in code, meaning I wouldn't be able to fill this dictionary I am looking for a way to easily associate my spells enums to the corresponding prefabs and animations |
0 | Unity Transport Layer API How to manage client server connections I am currently working on a "Master server" system for our Unity Game using Unity's Low Level "Transport layer API" for networking. My problem is that I would like to prevent clients from connecting to eachother. I have tried not giving them a port on the Addhost() call, but it doesn't seem to change anything. They also do not seem to detect the connections, so basically I find myself with NetworkTransport.Connect(..) calls that work (the error byte is 0, meaning no error) but no actual connections. I don't understand what's going on. I can't really show my code because it's quite long, but here's how it works, in summary The Clients objects initialise a Socket as normal with only one Reliable channel, no port, and one connection allowed by default. Then they have the ability to connect to another socket, as you'd expect. My problem COULD be coming from there for testing purposes the IP I use for testing is 127.0.0.1. What I do not understand is, how can it "find itself" when it is not bound to any port ? And more importantly how can it NOT find the Master Server object whose socket IS bound to a port ? Speaking about Master Server, it's an object that also initialises its socket, but with a port and many allowed connections. When a client connects and the connection did not yield any errors, it considers the connection to the Master server to be successful and proceeds sending a message containing some information for the server about this client the username chosen by the player for example. When the master server receives a connection event, it registers the received ConnectionID and waits for more information from that same connection, for example the aforementioned username. Both the client and the server handle receiving messages with the NetworkListener class (Static). On each frame it executes the Listen() method which executes a "normal" NetworkTransport.Receive() body. I can give you that part of the code as it is fairly common in design public static void Listen() int recHostID int recConnectionID int recChannelID byte buffer new byte 1024 int recDataSize byte error NetworkEventType e NetworkTransport.Receive(out recHostID, out recConnectionID, out recChannelID, buffer, 1024, out recDataSize, out error) Debug.Log("Listening") switch(e) case (NetworkEventType.Nothing) break case (NetworkEventType.ConnectEvent) Debug.Log("Connection established. ConnectionID " recConnectionID) if (OnConnectionReceived ! null) OnConnectionReceived(recHostID, recConnectionID, recChannelID) break case (NetworkEventType.DataEvent) Debug.Log("Received data !") BinaryFormatter f new BinaryFormatter() MemoryStream stream new MemoryStream(buffer) Message f.Deserialize(stream) as NetworkMessage break case (NetworkEventType.DisconnectEvent) Debug.Log("Connection terminated. ConnectionID " recConnectionID) break Network message is a simple data structure which contains a ConnectionID (the one it's from), a message title and content. The title is used to determine the general purpose of the message. The content is the rest of the information. What happens in my current build of the client The user is prompted to enter a username, then he clicks "Search for match". The search for match button is supposed to trigger the connection to the Master Server. The logs say that the connection was successful (as no errors are detected) but no Connection event is received on either side. This of course prevents everything else from working. If you need further description of the problem just ask and I'll answer ASAP. Thanks a lot in advance ! |
0 | Season Change Reveal Effect I was watching the teaser trailer for Seasons After Fall, and I was struck by the effect they use to transition between seasons (around 21 24 seconds) The level art, including the background and the foreground platforms, change from a sepia coloured autumn to a lavender winter, with the effect spreading outward from the player character a bit like water soaking through paper. It looks like more than just a palette change, as details in the leaf and bark patterns change in the transition. How could I achieve an effect similar to this in a 2D Unity game? |
0 | Jumping up quicker? (Paper Mario style jump) As shown here, Paper Mario's jump takes 8 frames go reach the max jump height and 12 frames to get back to the ground. This is pretty unusual, any idea how to jump up that quick with a rigidbody? I tried to AddForce when rigidbody.velocity.y gt 0, but that didn't work out. Any help would be appreciated, thanks in advance! Jump when pressing button and on ground jumpForce is a public float variable if (Input.GetButtonDown( quot Jump quot ) amp amp isGrounded) theRB.velocity new Vector3(0, jumpForce, 0) |
0 | How can I replace an object with a prefab so the prefab will be at the same position of the gameobject? I have some doors in the scene, each door at another position. I took one of the doors added to it a light and made a prefab of the door. Now I want to replace all the other doors with the prefab. Example of the door with the light I added and this door is also a prefab And this is example of another door that is not yet replaced by the prefab door with the light I want to replace this door with the prefab door with the light at the first screenshot. The question is if there is a easy way to do the replace ? I have more doors that I want to replace. |
0 | How to limit the speeding up of enemy movement? Is there a way of limiting my speeding my enemy script every time my player collects 10 points. I have a movement script attached to my enemies and every time my player collects 10 points my enemies get faster. I want to put a limit on that so that the movement script (attached to my enemies) doesn't increase all the time even if the player continue to collect 10 more points and onwards. I want the limit to be 40, so even if the player continues to collect another 10 points the movement should stay at 40. This is my speeding up my enemies script (this is used in my score script) if (Score 10 0) Increment movespeed variable from Movement script Movement.movespeed 4 And this is my movement script attached to my enemies public static int movespeed 20 public Vector3 userDirection Vector3.right public float lifetime void Start () Destroy (gameObject, lifetime) public void Update() transform.Translate (userDirection movespeed Time.deltaTime) How can I limit the movement speed so that it doesn't exceed the upper limit I want? |
0 | Blend Tree animation problems at rotation I have a Blend tree animation with two floats ( VelocityX, VelocityZ) that have idle, run , run right, run left , I use a pad to move it at world space When VelocityX is 1 it run left, 1 it run right When VelocityZ is 1 it run back, 1 it run foward It is working fine but the problem comes when I rotate the character in his Y axis, If I rotate the character 90 degrees on the Y axis, This system 'breaks' since blend tree is calculating VelocityX and VelocityZ from world space and not local space, So character is doing 'run foward' animation to go top but hi should do 'run right' animation since from character prespective he is moving to the right How I can implement that local rotation into my blend system? Any help or guide will be apreciated |
0 | How can I create a mirror with Unity? Can anyone explain how I can create a mirror effect like the one in this YouTube video using Unity Pro? I know that I need to use render textures to do it, but I am not sure how. |
0 | Antialiasing shader grid lines I would like to have in game grid lines similar to ones found in Unity editor. There is simple solution(first listing) based on shaders found on unity forums(on right image). However, that solution does not take in account antialiasing and drawn lines looks terrible even few units away from camera. float4 frag(vertexOutput input) COLOR if (frac(input.worldPos.x GridSpacing) lt GridThickness frac(input.worldPos.z GridSpacing) lt GridThickness) return GridColour else return BaseColour In order to address that, I tried using typical fwidth smoothstep combination float4 frag(vertexOutput input) COLOR float distX min(frac(input.worldPos.x GridSpacing), 1.0 frac(input.worldPos.x GridSpacing)) float distZ min(frac(input.worldPos.z GridSpacing), 1.0 frac(input.worldPos.z GridSpacing)) float dist min(distX, distZ) float delta fwidth(dist) float alpha smoothstep( GridThickness delta, GridThickness, dist) return lerp( GridColour, BaseColour, alpha) Even though it has nice fade, the result is not quite near to perfect not only the lines looks thinner(which can be somewhat fixed by increasing width), but also have various artifacts(e.g. in joints) and horizontal lines disappear much sooner than vertical ones. Detail image(anti aliased on left) I am interested in shader solutions, since according to answer to similar question relying textures there in can be no solution with textures. In addition I would like grid lines fade at reasonable distance(when closely inspecting aliased overview image you can see where plane ends) rather than continuing to infinity. Full current version(for testing purposes) with signed distance. |
0 | How to convert world coordinates to grid movement I'm producing a tactical 3D RPG game and I have the following issue I want the NPC to move through the grid. The grid is formed by tiles and each tile has a script attached to it. In this script, there is a variable called TilePosition which is a Vector2Int, that I use it to stores its X and Y values in the grid. The NPC character has a script attached to it called NPCPlayer, where a use a Vectir2Int named NPCGridPosition to stores its position in the grid. Also regarding the NPC, he has a script called NPCMovement. In this script, I've set a raycast that starts from the NPC feet and goes down. I use the raycast to take the TilePosition variable as it is written in the code public void MoveNPC() if (Physics.Raycast(transform.position, Vector3.down MaxDistance, out hitDown)) if(hitDown.transform.tag "Tile") Tile TilesPosition hitDown.transform.gameObject.GetComponent lt Tile gt () NPCPlayer NPCPosition this.GetComponent lt NPCPlayer gt () However, when I try to move the NPC through the grid, 3 rows ahead, he goes away, because he moves according to the world position, rather than moving according to his tile position. I'm using these lines of code to make him move public void MoveNPC() if (Physics.Raycast(transform.position, Vector3.down MaxDistance, out hitDown)) if(hitDown.transform.tag "Tile") Tile TilesPosition hitDown.transform.gameObject.GetComponent lt Tile gt () NPCPlayer NPCPosition this.GetComponent lt NPCPlayer gt () targetPosition.x TilesPosition.TilePosition.x 3 targetPosition.y TilesPosition.TilePosition.y this.transform.position Vector3.MoveTowards(this.transform.position, targetPosition,velocity) How could I make the NPC to move according to its position in the grid? I'll be glad if someone can help me a little bit with this. |
0 | Generate a large data structure using a compute shader I know that RWTexture2D Result void CSMain (uint3 id SV DispatchThreadID) Result id.xy float3(1,2,3) will result in an texture containing the numbers 1,2,3 however I'm now looking for a way to control a compute shader in such a way as to generate either a 3D texture with control over which order my operation occur or a way to fit a data structure in the return value of the compute shader. For a simplified example let's say that I want to generate either a 2D array of linked lists with each value in the linked list being equal to 1 the next value so 9 8 7 6 , 11 10 9 8 8 7 6 5 , 6 5 4 3 2 from the input texture 6,8 5,2 or store the same in a 3D texture (the real version will be more complex so we will not be able compute that 5 2 7 but instead have to relly on the fact that 5 1 6 6 1 7) Any idea how to do this? |
0 | How to calculate the stopping distance of a wheel collider? I have an 'AI' bus in my game that needs to pull over occasionally at a bus stop. What I want to do is change the acceleration and brake force based on the stopping distance of the bus. I don't want to simply use the distance between the bus stop and the bus because each time the bus pulls over, it could be traveling at a different speed. Right now it uses the distance between the bus stop and the bus. It doesn't really work well though because if a bus is traveling faster, it will take a longer distance to stop and will likely go past the bus stop. Same thing if it were going slower. How do I calculate the stopping distance my bus will take to come to a complete stop? |
0 | Instantiate from two values, each in separate array I have a problem with Instantiating GameObjects from floats in arrays, which I have to merge into one Vector2 (or Vector3). I have only two values in arrays GameObject somePrefab float value1 float value2 First I have to combine them into a vector, then Instantiate as many prefabs as the combined vector number is... Can anybody help me with how to merge these floats into a vector and instantiate? |
0 | Audio Clip not working on Collision when destroying an object So I made a game where you shoot a laser and if it hits the enemy it makes an explosion sound and destroys the enemy. The only thing is whenever I try to get the audio to play it doesn't which I assume is caused by the enemy being destroyed. I have tried to use the Play() methods and PlayOneShot() methods but they both don't seem to help me out. This is my current code public AudioClip explosion public AudioSource explosionAudioSource public void OnTriggerEnter2D(Collider2D other) void Start() explosionAudioSource GetComponent lt AudioSource gt () if (this.tag "Enemy" amp amp other.tag "Laser") explosionAudioSource.PlayOneShot(explosion) Destroy(other.gameObject) Instantiate(enemyExplosion, new Vector3(transform.position.x, transform.position.y, transform.position.z), Quaternion.identity) Destroy(this.gameObject) uiManager.UpdateScore() Thanks! |
0 | Remove delay when changing axis input in the Unity Input Manager I had a problem playing with the Input Manager, where for example When Horizontal ( ) is pressed, it increase its value but, when Horizontal ( ) is pressed, the horizontal value stays positive for a little, but keeps decreasing. This causes the character to continue playing "right" animations and still moving to right for a few seconds, instead of instantly playing 'left" animations and moving to left. The problem also makes the character movie a little after the player releases the key. I have also used Input.GetKey(), but that means the player cannot change the setting from the game launcher, and I don't want to create player setting in game, for now. What I am trying to achieve is when Horizontal ( ) is pressed, then the player presses Horizontal ( ), it should instantly turn left without delay. When the player is not pressing any Horizontal key, it should stop moving horizontally, instantly. This problem also appears along the Vertical axis. How do I make it so input snaps to 1 or 1, with out slowly moving back and forth? |
0 | What is wrong with my Chest script? I'm making an RPG in Unity3D and I am trying to make a script for a chest to open. So I built this script! But it doesn't work. I just want some help fixing this script. pragma strict var Text GameObject var OpenedChest GameObject var CurrentChest GameObject function OnTriggerEnter() Text.SetActive(true) if (Input.GetKeyDown("e")) CurrentChest.SetActive(false) OpenedChest.SetActive(true) function OnTriggerExit() Text.SetActive(false) I get no compiler errors. When I go into the collider that triggers the text, that works, but what doesn't is when I press E to open the chest. It doesn't activate the other chest. What is wrong with my script? |
0 | Allow code after a bugged line to continue without use of try and catch My problem is with C in unity, but I think the problem can be applied to all coding languages. For example I have a start function event that may initiate many things. Some lines of code may issue a bug but I want to allow new lines of code run after that without having to encapsulate every line of code with try and catch. Is there any common solution for this that I'm missing? |
0 | Getting location bounds of centered text I want to show a dialog box where the user should answer a question. It would look like this The question is aligned horizontally. I don't show the entire question text right away, but it builds up character by character like this To do that, I store the text string in a variable at the script start, then I set the text to "", and in a coroutine I add character after character to the text component. My problem is that (because of the horizontal alignment) Unity wants to build it up starting from the center like this Since this is not what I want, I was thinking that I should perhaps measure the bounds of the entire text while it is horizontally aligned, then I would turn off the horizontal alignment and make it left aligned instead and set its position according to the measure bounds. However, I don't know if I can measure the bounds of the text anyways. Can anybody suggest how to handle this problem? |
0 | Animator from another gameobject keeps disappearing from script on play I am working on a gun script and it worked fine until earlier today when I made a change to the script and it stopped working. I put it back, but for some reason now the animator object attached to the script keeps disappearing. using System.Collections using System.Collections.Generic using UnityEngine public class RifleShooting MonoBehaviour private float NextTimeToFire 0f private int CurrentAmmo private bool IsReloading false Space(10) Header("Floats") public float Damage 10.0f public float Range 100.0f public float ImpactForce 60f public float FireRate 15f public float ReloadTime 1.0f Space(10) Header("Others") Space(5) Space(10) Header("Others") Space(5) public int MaxAmmo 10 public Camera FPSCamera public Animator GunAnimations public ParticleSystem MuzzleFlash public GameObject impactEffect public bool AllowedToShoot true Start is called before the first frame update void Start() GunAnimations GetComponent lt Animator gt () if (CurrentAmmo 1) CurrentAmmo MaxAmmo private void OnEnable() IsReloading false GunAnimations.SetBool("Reloading", false) Update is called once per frame void Update() if (IsReloading) return if (CurrentAmmo lt 0) StartCoroutine(Reload()) return if (AllowedToShoot false) return if (Input.GetButton("Fire1") Input.GetButtonDown("Fire1") amp amp Time.time gt NextTimeToFire) NextTimeToFire Time.time 1f FireRate Shoot() IEnumerator Reload() IsReloading true Debug.Log("Reloading...") GunAnimations.SetBool("Reloading", true) GunAnimations.SetBool("IsShooting", false) yield return new WaitForSeconds(ReloadTime .25f) GunAnimations.SetBool("Reloading", false) yield return new WaitForSeconds(.25f) GunAnimations.SetBool("IsShooting", true) CurrentAmmo MaxAmmo IsReloading false void Shoot() shooting script here Also if it helps here is what I see in the console when I try to fire MissingComponentException There is no 'Animator' attached to the "M4A1" game object, but a script is trying to access it. |
0 | Using a object as origin for a Raycast using mouse position as direction Is there any way to cast a ray from an object using the mouse position as the direction for the ray? I ve been looking for a while but I can t find something like that anywhere, so if anyone could help with this it would be great. I m using kind of a top view, you can see how here And what I want to do is set a empty game object on top of the character to act as the origin for the ray, then when I press a key the mouse is unlocked and an area appears, here s how that looks And I want to use the position where the mouse clicks to be the direction of the ray. |
0 | Unity3d multiplayer canvas so I am making multiplayer game and I stuck on one thing, I have blood overlay canvas in my scene(you know, in fps games if somebody shoots you your screen becomes red and this stuff), and when I shoot enemy, his screen becomes red, but mine also. thats what i ahve now if raycast hits enemy, player script calls ColorController.MakeItred() color controller is attached to this canvas image, here is its code void Start () if (current 100 current 0) opacity 0 Update is called once per frame void Update () image GetComponent lt Image gt () image.color new Color32(reds, greens, blues, opacity) if (current 0) opacity 0 if (!playing) if (opacity gt 0) StartCoroutine(toLower()) if (opacity 255) playaudio() public static void MakeItred() opacity 255 public static void MakeItOff() opacity 0 void playaudio() AudioSource audio GetComponent lt AudioSource gt () audio.Play() private IEnumerator toLower() playing true opacity 1 yield return new WaitForSeconds(interval) playing false btw thats function in player code that calls colorcontroller.makeitred, ClientRpc public void Rpcdoit() ColorController.MakeItred() Nick thanks. |
0 | Upgrade items on shop menu I made a game and I made a Magnet upgrade and I have 8 game objects to set active 1 by 1 every time when I upgrade the magnet and I have (int upgrade 0 ). But when I upgrade these game objects it's set active, but if I quit the game and start again all these game objects are FALSE. How can I make e.g if I upgrade to (int upgrade 6) and to make my game objects active only from element 0 to element 6. I do upgradeMagnet() to void Update but its make active only 1 game object depends from (int upgrade) if (int upgrade) is 5 and only game object element 5 is active. public GameObject upgranded public int upgrade 0 public void upgrandeMagnetButton() upgrade 1 upgradeMagnet() void upgradeMagnet() if (upgranded upgrade ) upgranded upgrade .SetActive(true) |
0 | Lamba expressions The Operator. Any plain English help to understand this please? I've been adding Google Play support into my game. For the most part I'm getting on swimmingly, but I'm having a hell of a time understanding exactly how the submission calls to submit score and achievements work. It's the gt operator and surrounding method that confuse me, such as this one that I have in my code. It all works, I just don't know how. I've read up a bit and I think these are called Lambda expressions. But I want to know why it is this way, and why it isn't made so we can just use the standard typical bool instead of making this strange way to send the result of whether or not our player is logged in. Hope that makes sense. Here's the code in question Social.localUser.Authenticate((bool success) gt if (success) Debug.Log("score authenticed successfully") else Debug.Log("score not authenticed, check user is signed in") ) Social.ReportScore(score, GPGSIds.leaderboard pinball wizards, (bool success) gt ) Particularly, the bottom line really has me stuck. |
0 | Default mipmap level elements to use for CopyTexture in Unity Scripting? I want to make a tiled map. I want to use the function CopyTexture to copy from a Texture2D (where is stored my tileset) to a RenderTexture. I want to use the third overloading (with all the arguments) which allow me to choose from where in the source texture and where in the render texture I will copy. But I need to specify mipmap levels and elements. I don't know what to use as mipmap levels and elements in this function. Thanks to everyone who can help me ) |
0 | Integrating Unity physics with Entitas I've used Entitas a bit and it appeared to me as a great way of creating clean, modular code. I've seen few examples of games created with this framework, and most of them were puzzles, TD's, simple RPG's, etc. Those made me come to think, that ECS like that is not suitable for games making big use of Unity built in physics engine. Rigidbody in this case is part of View layer, but it would affect for example "position" component, so we can't say they are really separated. Unity Physics also works at it's own pace, so there is not really a chance for independent Component System based simulation. Are there any generally accepted solutions, or if I don't wan't to write my own physics engine, I should give up Entitas? |
0 | Getting scene normals in Unity When I get the depthnormals with the shaderreplace script, it just replaces all the shaders in the scene and uses the meshes geometry to calculate the normals, ignoring the normalmap textures applied on them. How can I get the final rendered scene normals to a rendertexture like it appears in the editor windows normal debug mode that is used for deferred light calculations and ambient occlusion and such ? |
0 | Adding large 3d models into Unity I have a 3d model of a restraunt with several characters in it probably over a hundred objects. Whenever I try to import it into Unity Unity just loads forever until I force close it. How do you import such large models without Unity crashing? |
0 | How can I manually call fire OnTriggerExit() for colliders a trigger is inside of in Unity? In Unity, the OnTriggerExit() method is not called fired (not sure if it's an event or not) when an object is disabled or destroyed within it's collider. In comparison to it being fired is an active object that was within it's collider no longer being inside the bounds of that collider on the next frame. I want to be able to call OnTriggerExit() on my triggers OnDisable() method as a workaround. How would I go about calling firing OnTriggerExit() manually? |
0 | Goalkeeper Jumping Algorithm? This may be a "best way to" question, so may be susceptible to opinion based answers (which is ok for me). But I would also like if there are any tutorials , research papers , etc. I'm trying to make a 3D free kick game, and I want to decide on the Goalkeeper algorithm. Usually (and in my game) the shot is a function of direction , power and swerve. Maybe wind can be a factor too. So the shots trajectory is pre deterministic, i.e., the point that intersects the goal (or out) plane is determined as soon as the shot fires. So what could be a good approach for the goalkeeper to jump (or walk) ? I have two approaches in mind 1 determine the point, and jump to there. 2 when the ball is closer than a threshold distance, estimate the point by the ball's velocity vector, and jump to there. The problem with the first approach is, goalkeeper will always save the shot, which I want to prevent. So there should be some kind of randomness, or the goalkeeper's ability to jump and walk will be restricted. The problem with the second approach is, when there is a high amount of swerve, the goalkeeper will always fail to save the shot. So how could these approaches be better? Thanks for any help ! Edit if you want to play the game, click here |
0 | Is Unity 2017 random number generator deterministic across platforms given the same initial seed? Is unity engines random number generator deterministic across platforms given the same initial seed or should I implement my own? I know there have been some modifications to the random number generator recently. Answers are appreciated, I don't have the devices on hand to perform any tests and I haven't yet found a direct statement on the matter. |
0 | How to properly format classes for JSON deserialization with JSON.net for Unity? UPDATE This answer has been solved and this post updated to I am creating an inventory system and decided to keep a master list of all the items. The goal is to use Newtonsoft's JSON.net to parse the item list and populate the database of items. The JSON item list looks like JSON "Ingredients" , "Consumables" "ID" "TP Small", "Icon" "Sprites porridge.png", "Name" "Small Tan Pill's Porridge", "Consumable" true, "Cooldown" 0, "Duration" 3, "Effect Description" "Restores 100 health.", "Description" "A hearty drinkable meal from everyone's favorite hypercellulose gelatin timelord!!!", "SFX" " eb4e9ad8 c6ac 414f 8d5e c3d012ca6ae6 ", "Bonuses" "HP" 100, "Stamina" 100, "Tolerance" 20, "Attack" 4 , "Concoctions" , "Equipment" , "Abilities" And this is the structure of the classes we are using to match the JSON Classes System.Serializable public class Items public List lt ItemBase gt Ingredients public List lt ItemBase gt Consumables public List lt ItemBase gt Concoctions public List lt ItemBase gt Equipment public List lt ItemBase gt Abilities System.Serializable public class ItemBase public string ID public string Icon public string Name public bool Consumable public int Cooldown public int Duration public string EffectDescription public string Description public string SFX public StatBonus Bonuses System.Serializable public class StatBonus public int HP public int Stamina public int Tolerance public int Attack The deserialization code TextAsset json Resources.Load lt TextAsset gt (path) itemList new Items() itemList.Abilities new List lt ItemBase gt () itemList.Concoctions new List lt ItemBase gt () itemList.Consumables new List lt ItemBase gt () itemList.Equipment new List lt ItemBase gt () itemList.Ingredients new List lt ItemBase gt () itemList JsonConvert.DeserializeObject lt Items gt (json.text) This code now works as intended! |
0 | Having multiple different friction values on a single piece of track? I am trying to figure out a good performant way to give a piece of track multiple values of dynamic friction. A track piece is 10x10 units in Unity and the idea is to puzzle them together to a big track like the tracks in Trackmania. The game itself features no acceleration, except from gravity. To make things more interesting I want to give each track piece at the start of the scene multiple random friction values within a given range. Currently I achieve this by making each piece of track consisting of 100 little tiles which are 1x1 units and they get a random friction values assigned. This approach works somewhat fine as long as there are less than 30 to 40 track pieces(3000 4000 tiles) but with more than that the fps are dropping really low. As it is a racing type of game I had to set the quot Fixed Timestep quot in the project settings to 0.001 to get accurate time measurments and this is hurting the performance as well. With a lower timestep the collision detection with all the little tiles is really bad too. Is there a more elegant and or performant way to achieve this in within the unity physics system? |
0 | Unity3D RigidBody adding force diagonally (x,y,0) results in two separate movements instead of one diagonal movement? The intentions of this function are to utilize the RigidBody component from a "target" object and clear its force while applying a diagonal force in the direction upwards and away from the side they are facing. I have omitted the portion in which detects the other direction for the sake of simplicity in reading the function as I've been testing this function while the user faces the right hand direction. Variables target refers to the other object currently in the scene targBody refers to the RigidBody component of the target object damage refers to the current damage integer of the object. The damage used in this instance is from the target object facingRight refers to a bool in which is true whenever the current object is facing the right hand direction. public void Damage() targBody.velocity Vector3.zero if(facingRight) Vector3 newVel new Vector3(target.GetComponent().damage 16, target.GetComponent().damage 16, 0) targBody.AddForce(newVel, ForceMode.Impulse) print("Stuff") target.GetComponent().damage 3 For some reason, when I apply the force, the target object doesn't move diagonally. Instead, it moves horizontally before moving vertically however, for some strange reason the horizontal speed is always greater than the vertical speed as it goes so fast that it nearly teleports! I'm not sure if this error happens because of a coding problem on my part that I'm just not recognizing or if it's a problem with RigidBody in which I need to use a workaround for.Anyone have any ideas on what can make this function work the way I want it to? |
0 | Unity SceneView Positionning object with mouse position in Editor script I would like to create an editor tool who can change the position of an object in the scene view into other object in the world, based on mouse position, like in the picture bellow (the red pyramid is my object to positionnate rotate) I would like to do a raycast from the scene view camera to the mouse position (or something like that), to get the gameObject over the mouse, and then get the position of the verticle normal for position and rotation of my gameObject For now, I have tryed some code who didn't work, I have my object named "preview", and inside the methode OnSceneGUI() in a editor script i have managed to move my preview object, but now I have to know where to put it... Thanks ! EDIT here some of my try Transform previewPoint here my transform void OnSceneGUI() PointCreator() private void PointCreator() test 1 Camera sceneCam SceneView.GetAllSceneCameras() 0 Vector3 spawnPos sceneCam.ViewportToWorldPoint(Event.current.mousePosition) previewPoint.position spawnPos test 2 Vector3 mousePosition Event.current.mousePosition mousePosition.y SceneView.currentDrawingSceneView.camera.pixelHeight mousePosition.y mousePosition SceneView.currentDrawingSceneView.camera.ScreenToWorldPoint(mousePosition) mousePosition.y mousePosition.y previewPoint.position mousePosition |
0 | How do I define a required component on a Unity game object? I have a script that expected the game object to have a Terrain component. Is there an attribute I can add (or some other way) which will prevent a designer from adding my script component MonoBehavior to a GameObject that does not have the Terrain component? The only alternative I have been able to find is to attach my script to something else, and then have a public Terrain field, which requires the user to attach the terrain object to it. (since the editor won't allow you to associate a different object type.) I just want the reverse. Any thoughts? |
0 | How to correctly implement custom tick system? I am making a custom tick system to suit my needs (calling normal ticks every 0.2 seconds, medium ticks every 5 seconds etc...) I followed the tutorial in this video CodeMonkey tick system tutorial In his tutorial, he implements the tick counting as shown private const float tickTimerMax 0.2f private void Update() tickTimer Time.deltaTime if (tickTimer gt tickTimerMax) tickTimer tickTimerMax Tick Happens every 0.2 seconds. OnTick?.Invoke(this, new OnTickEventArgs Tick Tick ) However, in other sources I have seen that instead of subtracting tickTimerMax from tickTimer, we just straight up set the tickTimer to 0, as shown if (tickTimer gt tickTimerMax) tickTimer 0 Tick It's hard to say if there's a big difference between these two methods, because at first glance they seem to do the same thing, but clearly they have their differences. So I'm wondering, which one I should use? |
0 | Camera is centered on character, but doesn't show character in game window I'm using Unity 4.6.3. I create an animation from sprite. When I press Play button, I see animation plays on scene window, but on Game Window, I don't see anything. Here is Inspector for main camera Here is Inspector for Player I have checked that both z 0 when execute. Please tell me which part I config wrong ? |
0 | Unity test Play mode window problem I tried to find an answer to his problem but i wasn't successful. When i press play to test my game, instead of the play mode going to the Game tab and play the game there, with all the unity tabs and options still on the screen, it goes almost full screen, all of the unity window goes to the game mode and i can't see anything but the game, to see the scene, options, etc.. again i need to stop the play mode. For example, if i want to test triggers in play mode, i can't because all i see is the game window. How can i test the game just in the Game tab? Perhaps i changed some setting. I'm not sure if im explaining my problem correctly. Thank you |
0 | Align UI element to gameObject in 2D I have a 2d game where I want to display UI element perfectly aligned to specific gameObjects. I have an ortographic camera and I used to Camera.main.WorldToScreenPoint() function giving it the gameobject position modified, for instance, by 1 on X component to get the UI element on its perfect right. My problem is that the element is not on the gameObject's perfect right, but sensibly above. See this schema Expectation G UI element Reality UI element G I tried also to use the WorldToViewportPoint() but it's not giving the desired result. So, I think this is the right way to go but I can't guess what I'm missing. Any clue? EDIT After a little bit more observations it seemed that the UI element alignment depends somehow on it's distance from the center of the screen (of the camera viewport I guess), so that if the gameObject is below half height the UI element y position won't be on the perfect right but slightly below it and if above half heigth will be slightly above the perfect right. Same for x coordinate. Is there a way I could control this? |
0 | unity read from text file to instantiate objects I'm trying to use the following code to read a text file stored in the Resources folder or in a file on my computer, and instantiate objects in a Unity 3D scene accordingly. I'm having trouble getting it to work. I've tried attaching the script to either the main camera or an empty gameobject. Neither work so far... I either end up with an error saying the path does not exist (when I put the text file into the project folder on my desktop), or a null exception, or that the path contains invalid characters. Where am I going wrong? I'm trying to use a jagged array because I'll need users to eventually be able to change the text file on the go to create a level. The text file contains the following data S 0 0 0 1 0 0 1 0 2 2 0 0 2 1 My script currently reads using System.Collections using System.Collections.Generic using System.Text.RegularExpressions using UnityEngine using System.Linq using System.IO using UnityEngine.UI public class GenerateLevel MonoBehaviour public Transform player public Transform ground public Transform floor valid public Transform floor obstacle public Transform floor checkpoint public const string sfloor valid "0" public const string sfloor obstacle "0" public const string sfloor checkpoint "2" public const string sstart "S" public string textFile "maze" string textContents Use this for initialization void Start () Instantiate(ground) TextAsset textAssets (TextAsset)Resources.Load(textFile) textContents textAssets.text string lines System.IO.File.ReadAllLines(" maze.txt") string textFile textFile Resources.Load("assets resources maze").ToString() string jagged ReadFile(textContents) for (int y 0 y lt jagged.Length y ) for (int x 0 x lt jagged 0 .Length x ) switch (jagged y x ) case sstart Instantiate(floor valid, new Vector3(x, 0, y), Quaternion.identity) Instantiate(player, new Vector3(0, 0.5f, 0), Quaternion.identity) break case sfloor valid Instantiate(floor valid, new Vector3(x, 0, y), Quaternion.identity) break case sfloor obstacle Instantiate(floor obstacle, new Vector3(x, 0, y), Quaternion.identity) break case sfloor checkpoint Instantiate(floor checkpoint, new Vector3(x, 0, y), Quaternion.identity) break Update is called once per frame void Update () string ReadFile(string file) string text System.IO.File.ReadAllText(file) string lines Regex.Split(text, " r n") int rows lines.Length string levelBase new string rows for (int i 0 i lt lines.Length i ) string stringsOfLine Regex.Split(lines i , " ") levelBase i stringsOfLine return levelBase |
0 | Obscure primitive data types against cheating im trying to create lightweight value obscurer, against possibility to blatantly change primitive values in memory editor. Such as cheat engine. Here's what i have to far. lt summary gt Obscure for type int. lt summary gt public class ObscuredInt public ObscuredInt() this.value 0 public ObscuredInt(int value) this.value value private int a private int b lt summary gt Current obscure value. lt summary gt public int value get return a b set a Random.Range(int.MinValue, int.MaxValue) b value a usage ObscuredInt health new ObscuredInt(5) health.value 10 printInConsle(health.value) This works by simply never storing actual value, but rather a combination of two integers, which sum represents the value. That way the value is actually never cached long time in the memory. So finding it in a primitive way using cheat engine is not possible. My question I've seen other examples of obscuring, which involve conversion to binary or string hashing or other quite heavy operations. This example is of course much more lightweight, how is this example worse than more advanced hashing or conversions. What flaws do you see with this example? What can you suggest? Thank you |
0 | Using Burst Compile attribute on methods Can we use BurstCompile attribute without using any Jobs or ECS System in Unity? does adding BurstCompile attribute before methods bring us any benefits? |
0 | How can I implement the traffic( drawing) functionality in the game? I am a beginner game developer. Games such as "Cities Skyline", "Simcity", "Citybounds", and "Traffic lanes 3" directly build roads and show simulations of cars moving over them. I have no knowledge to make these things. I can use Unity, construct2. How can I express things like roads, lanes, intersections, snapping, traffic simulations, path finding, driver AI, traffic lights, even wheels on the road? Road drawing Traffic simulating |
0 | Project transfer, will re importing all my models damage my project at all? Recently I had to transfer my Unity game project to another computer and downloaded the same version of Unity I was using for my 3D project and checked that all the files and folders were in the same place and everything. When I start up the game though my models have vanished and in the hierarchy it just says missing prefab instead of telling me what it was, like it used to if I'd move a model to another folder or something like that. It shows all my files there and I was about to reimport them all but I got a warning that said "Rebuilding assets is only if your project has been corrupted due to an internal Unity bug. It can take several hours to complete, depending on the size of your project. Please submit a bug report detailing the steps leading up to here." I am sure that re importing all my models will fix this but I want to ask if this will have any negative effects on my project or possibly damage anything? This game is extremely important to me and I've been working on it for the past 3 years(being self taught which is why it's taken so long and I'm still learning) Thank you guys in advanced! D |
0 | Why is anti aliasing not being applied to my 2D objects in Unity? I am drawing 2D objects in Unity. Some of these objects are drawn using the standard sprite method that is built into Unity. Others are computed as distance functions in a shader. In both cases I can't get Unity to apply anti aliasing despite the setting being set. Is there an extra step that I am missing that is required to get anti aliasing to work properly? Would it be better to implement my own form of AA in a shader? |
0 | Is it more efficient detect when audio clip ends with AudioSource.isPlaying or with AudioClip.length? In Unity, I want to trigger an event when an audio clip finishes playing. Would it be more CPU efficient to keep checking if the audio clip is playing with WaitUntil(() gt audioSource.isPlaying false) or would it be more efficient to use WaitForSeconds(audioClip.length) to simply wait a certain amount of time? How can I run a test in Unity to see which one is more CPU efficient? |
0 | Regarding Profile Pictures of Facebook Friends Background I am creating a Leaderboard of Facebook friends in unity. Question Can we download and save the images of Facebook Friends on the device of the user for the purpose of reuse? I would like to store the images of the FBFriends on the user's device so that there is no need to download the same pictures everytime the game is restarted. Is it legal to do so? I asked the same question in Facebook Developers forums but I did not get any response. Kindly guide me. How do devs build a leaderboard of Facebook friends normally? Thankyou. |
0 | 3D visual effects on videos I'm trying to get some hands on experience with 3D visual effects on videos. Similar to those AR apps, I want to add a 3D model with effects, say a dragon, to a video. Something like this famous demo https youtu.be u5hQpRbHERg But I don't really want to make it this fancy with camera tracking. I like to start with the simplest approach probably just placing a dragon on the field (like its last scenes) with fixed camera. What's the best way to do it? Some tutorials would be very helpful. |
0 | Cave lighting in Unity I have a cave that is inside a mountain (one mesh) that I created in Blender. I would like to make the cave quite dark inside so that either the player can light it up, or it is lit up with things such as crystals. Because I have ambient light through the scene, it's proven to be quite awkward to make it dark, and removing the ambient light kinda destroys the look. I then played around with having a separate material for inside the cave so that I can make it darker, which kinda worked, but then I noticed a big issue with shadows. The following images is from inside the cave far from the entrance. The first image is with the default settings for shadow distance (in this case it was 70 in the quality settings). As you can see in the image, the shadow doesn't fill the cave because of the distance. Second image is with the shadow distance turned up to make sure the cave is in darkness (not pitch black though, due to ambient lighting), this took the setting from 70 to around 500. The problem with setting the distance so high, is that it causes artifacts on geometry outside the cave, which look nasty. What's the best way to make a cave dark (doesn't need to be pitch black) without removing ambient lighting for the whole scene? I was looking at similar art styles to what I am working on, and Grow Home (Unity) is basically where I am heading. They have caves which would be acceptable for what I need, but am not sure how they done it. As far as I know, they have dynamic lighting, as I believe there is a day night cycle, so I don't think anything is baked. |
0 | No Support for UnityScript (JavaScript) on 2018.3 Hey I ve been working on a project for over 3 years and yesterday I have updated the unity from 2018 to 2018.3 and lost support for JavaScript. All of my scripts attached to gameobjects are there but not working while playing the game. I ve tried the UnityScript to C website but didn t work. I m a macOS user so couldn t use the converter tool on git (because it s been developed only for windows). I ll appreciate any suggestions. |
0 | Shader to see silhouette through alpha blended sprites I want to achieve in Unity a see through effect like the one in these examples In my specific scenario there are a couple of requirements Sprites are using alpha blending, and sprites have transparent areas. There are 2 kind of elements that occlude the character. One should create the silhouette effect, and the other one should behave like normal. For occluding elements that create the silhouette I enable ZWrite, and disable it for elements that doesn't. For the character I tried setting the queue of the shader to transparent 1, and added this pass Pass ZTest Greater Lighting Off Color Color And the effect works partially The silhouette is drawn all over the character, even the parts that are transparent. Transparent parts shouldn't create a silhouette. The silhouette is created when the character is behind a sprite, even if that part of the sprite is transparent. Being behind a transparent part of the sprite shouldn't create the silhouette. The character appears infront the rest of the elements, even if it is behind them. I guess this is because setting the queue to Transparent 1. But if I leave it as Transparent, the character is drawn in the correct order, but the silhouette is never seen. I tried to follow these tips someone gave me, but I'm unable to get it to work 1) Leave the pass that renders the sprites as is. 2) Add a pass that writes to the z buffer, but has a shader that uses clip() to discard pixels based on alpha. You can't use the z buffer to make soft z tests without using MSAA and alpha to coverage. The quality of that won't be great, but it's the best you can do. A faster alternative is a pattern or noise dither, or a good old fashioned threshold if your sprites all have fairly sharp edges. 3) Add third pass to occludable objects that draws the occlusion color using the z test and make sure it's drawn as a final pass. I'm kind of new to shaders, specially in Unity, and I just can't figure out how to make it work properly. |
0 | Using Physics.Raycast inside OnCollisionEnter2D function void OnCollisionEnter2D(Collision2D collision) foreach(ContactPoint2D contact in collision.contacts) RaycastHit raycastInfo Physics.Raycast(contact.point, Vector3.forward, out raycastInfo, 1000.0f) if(raycastInfo.collider) Debug.Log("Hit!") I am using this code to raycast an abject with the contact position of collision. The collision part works fine, when collision happens this function is triggered. But when I raycast to that position, RaycastHit variable return empty. I couldn't find what I am doing wrong. |
0 | How to avoid spaghetti in the animator? I am working with animations in Unity and so far I have made only four (Up Down Left and Right) and my animation window looks following... Problem is that if I was moving Up I want hero to stay looking Up not go to 'neutral idle' (or however he started), but that means I have 4 Idle positions... and each of them can transition to Up, Down, Left or Right and they go exponentially with each additional action... Which makes me feel like I am doing something wrong.... Is there a better way of making transitions between different actions? |
0 | How to randomize Motion animation without create a state for each animation? I'm using Animator and state for animating my charachter. So, i've (example) an Idle state, associated to an Idle motion animation , and a Death State, associated to a Death animation. But I've 5 possible animation for death so i would like to randomize death animation without create a state for each animation. My State "Death" has a "Motion" variable. I would like to change at runtime this "motion" variable. Is it possible ? Thanks |
0 | Help needed, following Unity multiplayer Health Bar tutorial. Only working on Server Host instance of the game was really hoping someone can be good enough to look over my code, I've been trying to fix it for several days. I followed the Unity tutorial which is fairly basic but the bit that confuses me (and potentially where the problem lies) is the if (!server) return part at the top of my TakeDamage() function. The problem im seeing is that once I get to that part of the tutorial, the bullet fired by the Host is registered against the other player and I can see his health has gone down (great so far!) , but when I load the instance in the editor (i did running another standalone on my laptop and connect to internet matchmaking but the same thing occurs) his bullets are not registered (even though my debug log tells me the Ray did hit the player. The tutorial tells me to make it return if not server, it then uses SyncVar and a hook that is supposed to call the method "OnChangeHealth" whenever currentHealth is changed. This DOES NOT appear to be happening, and the TakeDamage code is only happening on the Server Client Host instance. I was trying to adapt the tutorial to my own game, so there are some slight differences in the function and class names, but to me it looks to be exactly the same functionality wise. I will have to just post my full code here as I don't know which part is causing the issue (MANY THANKS FOR READING AND OR HELPING) the Player class public class Player NetworkBehaviour private GameObject startScreen public const int maxHealth 100 SyncVar(hook "OnChangeHealth") public int currentHealth maxHealth private float playerHeight private AudioSource audioSource public AudioClip painBodySound public AudioClip painHeadSound public AudioClip painHeadSound2 public RectTransform healthBar void Start () startScreen GameObject.FindGameObjectWithTag("StartScreen") if (startScreen ! null) startScreen.SetActive(false) playerHeight GetComponent lt Collider gt ().bounds.size.y currentHealth maxHealth audioSource GetComponent lt AudioSource gt () void Update () if (!isLocalPlayer) return if (Input.GetKey(KeyCode.LeftControl)) transform.localScale new Vector3(1, 0.5f, 1) else transform.localScale new Vector3(1, 1f, 1) public void TakeDamage(Vector3 hitPoint, int bulletDamage) check that its Server so that damage only gets applied on the server if (!isServer) return currentHealth bulletDamage audioSource.PlayOneShot(painBodySound) if (currentHealth lt 0) currentHealth 0 Debug.Log("Dead!") private void OnChangeHealth(int health) healthBar.sizeDelta new Vector2(health, healthBar.sizeDelta.y) Inside the bullet class is this function private void CastBulletRay() ray new Ray(bulletSpawnPos, bulletSpawnDirection) if (Physics.Raycast(ray, out hit, bulletRayDistance)) if (hit.collider.tag "Baddie") Debug.Log("ray has hit a baddie") Destroy(gameObject) if (hit.collider.tag "Player") Debug.Log("ray has hit a player") hit.collider.gameObject.GetComponent lt Player gt ().TakeDamage(hit.point, bulletDamage) Destroy(gameObject) and inside The Unity RigidBodyController class I'm using, I added Command void CmdFireBullets() muzzleFlashObject.SetActive(true) audioSource.PlayOneShot(gunFireSound, 0.2f) Create a new bullet GameObject newBullet Instantiate(bulletPrefab, bulletSpawnPoint.transform.position, bulletSpawnPoint.transform.rotation) as GameObject Spawn the bullet on the clients NetworkServer.Spawn(newBullet) |
0 | How can I parse different types of objects from JSON? I'm trying to save the player's inventory as a JSON data but I'm having a problem. I have a class Sword which extends an abstract class Weapon which extends another abstract class called Item. This is what JSON file looks like with the Sword and Armor objects in it "category" "type" "Weapon", "subtype" "Sword" , "id" 0, "value" 1, "name" "Wooden Sword", "description" "Sword made out of wood", "slug" "wooden sword", "stats" "wear" 100, "damage" 5 , "category" "type" "Armor", "subtype" "Helmet" , "id" 1337, "value" 1, "name" "Steel Helmet", "description" "Whatever...", "slug" "steel helmet", "stats" "wear" 100, "defence" 5, "vitality" 3, "dexterity" 1 How can I parse these objects into their respective C objects, putting the first entry into a Sword object and the second one into a Helmet object. There will be other types of objects in there too, so it's not limited on these two. |
0 | Unity's Android Notification system works on my Xiaomi, but on a Huawei every notification has an "Unknown" status? When my app starts I check whether there is a notification or not if there isn't I create one via SendNotification(...) if there is, I check their status var status CheckScheduledNotificationStatus(notificationId) On my Xiaomi their status is Scheduled, so I update them SendNotificationWithExplicitID(...) But on a Huwaei it's always Unknown, in that case I create a new SendNotification(...) And replace the old ID in the PlayerPrefs. But on the next startup it's unknown again. Maybe I should use SendNotificationWithExplicitID(...) as well when the status is Unknown so I can keep the ID? Here is the code var notification CreateNotification(jsonWrapper.Name, fireTime, title, text) if (PlayerPrefs.HasKey(jsonWrapper.Name)) var notificationId PlayerPrefs.GetInt(jsonWrapper.Name) var status AndroidNotificationCenter.CheckScheduledNotificationStatus(notificationId) if (status NotificationStatus.Scheduled) AndroidNotificationCenter.SendNotificationWithExplicitID(notification, "default", notificationId) Logger.Log( "Updated a notification jsonWrapper.Name at fireTime .") else if (status NotificationStatus.Unknown) var id AndroidNotificationCenter.SendNotification(notification, "default") PlayerPrefs.SetInt(jsonWrapper.Name, id) PlayerPrefs.Save() Logger.Log( "UnknownStatus Registered a new notification jsonWrapper.Name at fireTime .") else var id AndroidNotificationCenter.SendNotification(notification, "default") PlayerPrefs.SetInt(jsonWrapper.Name, id) PlayerPrefs.Save() Logger.Log( "Registered a new notification jsonWrapper.Name at fireTime .") |
0 | How to rotate object just like in the scene? Look at this image, I selected an object and pivot is set to local When I rotated selected object in the scene by X axis, it rotates exactly I wanted. But if I rotate axis from inspector or script, it doesn't rotated to desired angle. I'm not sure, but it seems it's related about Quaternion, but everything I tried doesn't worked well. How do I rotate that object just like in rotated from scene? |
0 | How can I retain the soundtrack state across levels to have continuous play? Suppose I have two levels. I want the same soundtrack to play on both of them. At the moment I have an audio source in each level, playing the soundtrack. However, when you move from one level to the other, the soundtrack will of course restart over (because it's a different audio source). How can I "resume" the soundtrack? Or rather, how can I retain the soundtrack state across levels to have continuous play? |
0 | Unity C Game Object Movement Issue I'm trying to move a game object within a set x and y range. I thought the code below would work, but it does nothing. The idea is the player controls the platform and tries to move under the ball. Any suggestions would be appreciated. using UnityEngine using System.Collections System.Serializable public class Boundary public float xMin, xMax, yMin, yMax public class PlatformController MonoBehaviour public float speed 10f public Boundary boundary public Rigidbody platformRB void Start() platformRB GetComponent lt Rigidbody gt () void FixedUpdate() float moveHorizontal Input.GetAxis ("Horizontal") float moveVertical Input.GetAxis ("Vertical") Vector3 movement new Vector3 (moveHorizontal, moveVertical, 0f) platformRB.velocity movement speed platformRB.position new Vector3 ( Mathf.Clamp (platformRB.position.x, boundary.xMin, boundary.xMax), Mathf.Clamp (platformRB.position.y, boundary.yMin, boundary.yMax), 0f ) Here's how the rolling ball works (as is intended) using UnityEngine using System.Collections public class BallMovement MonoBehaviour public Rigidbody ballRB public float thrust Use this for initialization void Start () ballRB GetComponent lt Rigidbody gt () Update is called once per frame void FixedUpdate() ballRB.AddForce (Vector3.right thrust) |
0 | After building a .exe file game view does not show whole viewport So, I went to build a game today in a .exe, and when I build it, it doesn't show the whole viewport as it does in the unity engine itself. So the game is cut off. It does this no matter what I do. What I see in Unity What I get running the exe Anyone know what's causing this? |
0 | Animation import What am i doing wrong? I need some help with an Animation that i want to import with Humanoid type (made in Blender). Essentially i made an animation in blender with IK FK (Rigify, with a bone for the sword, and IK to the hand). This is the preview in blender https i.gyazo.com 4f197c5e0ff1b291b45399fb4325ffc9.mp4 And this is when i import and set the animation with humanoid (activated the mask on the sword bone, parented with the root bone) https i.gyazo.com b042c29895be8e3db93edaa22e2a3665.mp4 In Blender i keyed IK and FK swith with the slider of Rigify, so i can move the hand without sliding. What i'm doing wrong? This is the Blender Rig (Rigify) with the sword bone https i.gyazo.com 00a1f9f523e67c0371b7f00e48c58ae9.mp4 |
0 | How to slide a non kinematic rigidbody? I'm studying Unity3d, coming from a 2d background, and I'm a bit confused how some things work. I'd like to slide a non kinematic rigidbody, i.e. "just move it forward", like if it was hovering over the terrain. Applying a force makes a ball rotate forward, while I wanted it to slide forward without rotating, also unless that force is huge, a cube just won't move (for the same reason). I understand there are kinematic objects which are "easier" to "just move", but I both think I might really need non kinematic ones, and I think I need to understand them anyway. edit I did try to use some "rotation constraints freeze", but they just prevented the sphere from moving at all. |
0 | Create a stack driven coroutine based state machine for Unity I am working on a game where I am using a coroutine based state machine which is mostly a multi class implementation of this link. I am using it because it allows me to create multi frame sequences. I wanted to know how would I go about making a stack based machine, so that I can overlay game states such as when I want to pause the game to show a menu i can run a pause menu state pausing the running game state, while still allowing the state objects to be rendered in the background Here is the code I am using for a state public abstract class State Inject MonoBehaviour gameObject Inject public EventSystem eventSystem StateMachine parent public State(StateMachine p) parent p public abstract IEnumerator Enter() public abstract IEnumerator Exit() public abstract IEnumerator Update() public IEnumerator Run() yield return gameObject.StartCoroutine(Enter()) while(parent.CurrentState.GetType() GetType()) yield return gameObject.StartCoroutine (Update ()) yield return gameObject.StartCoroutine (Exit()) State machine run function State Current The current state , the one at the top of the stack while(Current! null) yield return Component.StartCoroutine(Current.run()) The problem with this approach is as soon as the state machine's current state changes (That is when i push it down the stack adding a new state on top) , the while loop in the Base state class's run method will end and will call the exit coroutine causing the state to end which is undesirable as according to the stack pattern the state should be paused Moreover as coroutines work in unity, the yield return statement(in the state machine) wont return until the previous started coroutine exits , which is currently as of now responsible for starting the states . My question is how do i alter this code so as to pause the previous state (that will be pushed into the stack) instead of exiting it and starting anew state this implementation works fine if there is to be only a single state in the memory |
0 | UNET spawn dynamically generated object unity Spawning works when all clients are connected, but if a client connects after I spawn all my prefabs there are errors. I spawn the object before changing its Rigidbody's velocity, which seems to cause the problem. I spawn objects, change them, then the other client joins, and the errors come. these are the errors Failed to spawn server object, assetId 953c1c6ecbb84304280d1334ef5dae0b netId 26 I also make changes to variables on other scripts. All objects have network identities, network transforms, and are spawnable prefabs. |
0 | Calculating the weight of an object irrespective of the triangle or vertices count in Unity I have a meat piece which I want to weigh. Now there can be anything like fish, cheese, or other items that we can cut and measure. I want the weight to be determined by myself instead of determining from getting the surface of the item as it varies with different tris count. Currently, I am calculating the weight from the following code. public static float CalculateSurfaceArea(Mesh mesh) var triangles mesh.triangles var vertices mesh.vertices double sum 0.0 for (int i 0 i lt triangles.Length i 3) Vector3 corner vertices triangles i Vector3 a vertices triangles i 1 corner Vector3 b vertices triangles i 2 corner sum Vector3.Cross(a, b).magnitude weightMultiplier is a constant value for getting a reasonable weight value. return (float)(sum 2.0) weightMultiplier So if there's a meat piece like bellow and I want it to be a weight of let's say 3kg(6.6lb) then when I cut it into half it should give me values respectively (1.5kg). So I want the weighing factor to be in my control so that if in the future we have really detailed high poly items the weight shouldn't get affected by that. |
0 | How hard is it to port games from the PC to other platforms? I am trying to learn game development with the Unreal Development Kit and Unity, trying both out, and trying to get an idea how they work. For now, I'm mostly focusing on PC games. How hard is the technical aspect of porting a PC game that I made in the Unreal Development Kit or Unity to another platform, such as Play Station 3, or Xbox 360? is there some kind of option where we can just select the target platform from a combo box and press deploy, or do we need to modify the game for each platform? |
0 | How can I call Schedule() on interface that inherits from IJob So I have a voxel terrain engine, and I have an interface that all meshing jobs should inherit from. That looks like this (simplified from the actual) public interface IMesherJob IJob VoxelDataVolume lt byte gt VoxelData get set NativeArray lt MeshingVertexData gt OutputVertices get set NativeArray lt ushort gt OutputTriangles get set One example of a meshing job is marching cubes, which looks like this public struct MarchingCubesJob IMesherJob So here's my question If I have a reference to an IMesherJob, can I somehow call Schedule on it? If I have a reference to MarchingCubesJob, I can call Schedule on it This works MarchingCubesJob myMeshingJob GetMeshingJob() JobHandle handle myMeshingJob.Schedule(voxelCount, 64) But this does not work IMesherJob myMeshingJob GetMeshingJob() JobHandle handle myMeshingJob.Schedule(voxelCount, 64) I noticed that Schedule() is an extension method for T where T struct, IJob so that might be interfering with it, but it should still work because IMesherJob inherits from IJob |
0 | Accessing a char array from another class I'm working on a crossword puzzle game. In order to set the letters in my tiles, I have a script attached to text components that accessing a char array that stores my letters. It looks like this First class public class GenerateBoard MonoBehaviour public static char , gameBoard new char 15,15 void Start() gameBoard 0, 0 'W' Second class public class SetLetter MonoBehaviour Text letter public int x public int y Start is called before the first frame update void Start() letter GetComponent lt Text gt () letter.text GenerateBoard.gameBoard x,y "" Update is called once per frame void Update() Debug.Log("glitch " GenerateBoard.gameBoard 0, 0 ) I would expect Debug.Log to print 'W' but it appears to be empty. Why isn't it accessing the letter 'W' from the first class? When I use Debug.Log in my first class it properly prints 'W'. |
0 | admob ads problem in uity In unity 2019.1.3f I want to implement google admob ads in that game but after importing GoogleMobileAds v3.18.0.unitypackage in to my project I got a porblem. when I hit play button this window poped up. Please help me regarding the problem Thank you |
0 | GameObject not exiting through leftScreen I'm trying to wraparound game object so that, it exits through right screen and enters through left and vice versa. The code snippet below is what I'm working on. Vector3 Pos mainCam.WorldToScreenPoint(transform.position) Vector3 LS mainCam.ScreenToWorldPoint(new Vector3( 1, 0f, 0f)) Vector3 RS mainCam.ScreenToWorldPoint(new Vector3(1, 0f, 0f)) if (Pos.x gt Screen.width) transform.position new Vector3(LS.x, transform.position.y, transform.position.z) if (Pos.x lt 0) transform.position new Vector3(RS.x, transform.position.y, transform.position.z) So far, exit through right and re enter through left works, but the gameObject does not exit through the left screen, there seems to be a barrier preventing it, or maybe my parameters for the second if statement are wrong. |
0 | How to merge Sorting Layers in Unity? I have two unity3d projects, both are using sprite renderers and sorting layers. Project 1 has Following Sorting Layers Default Tile Map Items Animals UI Particles Project 2 has Following Sorting Layers Default Background Slots Chips Foreground Map UI Project 1 is my main project. I need to merge these both projects. I created new layers in project 1 and then imported project 2 but sorting layers of project 2 are broken .Setting each layer again in project 2 is very difficult task and rework. How can i merge these two project without breaking any sorting layer or tags ? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.