Handling rotation interpolation at 180 degrees I currently have a scene where 3d a gents move throughout a grid, each time they move that can pick a random cardinal direction up,down,left or right. They then rotate to face that direction using Quaternion.Slerp. However I noticed there were some edge cases where the agents didn't move at all, and found out the problem was being caused during rotations at 180 degrees. Doing some reading on this I found that Slerp and Lerp dont handle rotations at this degree very well if at all and now I'm at a loss on how to proceed. I tried using transform.rotateAround() to rotate the character around the Y axis to the direction, but again at 180 degrees the agents start to just spin in circles forever. Here's my current rotate code IEnumerator rotate() while(Quaternion.Angle(transform.rotation,direction) gt 0.3) var tempRotation Quaternion.Slerp(transform.rotation, direction, Time.deltaTime rotateSpeed) this.transform.rotation tempRotation yield return null this.transform.rotation direction Heres the code that handles picking where to go int choice Random.Range(0,4) prevPos pos if((choice 0) amp amp pos.x lt gs.maxX) pos.x 1 direction Quaternion.AngleAxis( 90,Vector3.up) else if((choice 1) amp amp pos.x gt 0) pos.x 1 direction Quaternion.AngleAxis(90,Vector3.up) else if((choice 2) amp amp pos.y lt gs.maxY) pos.y 1 direction Quaternion.AngleAxis(180,Vector3.up) else if((choice 3) amp amp pos.y gt 0) pos.y 1 direction Quaternion.AngleAxis(0,Vector3.up) If someone could point me in the right direction on how to handle this gracefully I'd really appreciate it!


Raycast implementation in order to optimizate collision detection I want to know if a gameobject (a plane) is facing another one to prevent collisions. Right now I have an array that contains all planes in the scene and, for each one, compare position in order to detect if is facing it or not. The number of planes is small, but I want to increase it and this method is a little... Mean. I was thinking to implement a raycast to detect if the gameobject has another one in front of it. Is it worth? Will it be less expensive? I think that raycast it's very expensive. In addition, I think that I will have to run three raycasts for every plane. Obviously this is not executed every frame, but every two seconds.


How can I represent collection of distant but visit able stars while using minimal resources? I have recently started to plan a project in Unity that will be for Android. I have a database that consists of over 150,000 stars (may trim this down if I O cripples the overhead). The game will hopefully consist of a free to explore universe creating the illusion that the user is flying in a realistic representation of the stars. My biggest concern at the moment is how do I create a realistic environment with these starts, while keeping the resource impact on the phone to a minimum? Some people mentioned using octrees, would this be wise? This is my first game that I am looking to create so any help would be much appreciated to this novice!


1 Texture For Multiple Models, Or 1 Model Using Different Textures For Each I'm creating some voxel flowers that are exactly the same, just different colours. Is it better to create 5 models and use 1 texture that has the 5 different colours, or create 1 model and use 5 different textures for each colour? Am curious as to which is more efficient in regards to performance, as there could be quite a few flowers on screen. I'm playing around with MagicaVoxel and Unity.


Not able to find the constraints option in the Rigidbody component I am working on a game tutorial right now and I need to freeze constraints for a model prefab. I add a Rigidbody component and I want to freeze rotations on the x and z axes. However, I am not able to find the option in the component. Is there another way to access rotation constraints (I do not want to code the constraints at the moment)? Or is there something I am missing in the new version. Please do let me know. Thanks I am using Unity 5.6.7f1 Personal


Client projectile ignores camera Y axis in multiplayer shooter I'm able to spawn the bullet and make it move. But the problem is, only the host can shoot the bullet in the way the camera is facing(takes both X axis and Y axis correctly). The client takes only the X axis of the camera and keeps the Y axis at zero. Here's the code for spawning and applying velocity Command void CmdFire() GameObject fb Instantiate(fireBall, spawnPoint.position, spawnPoint.rotation) fb.GetComponent lt Rigidbody gt ().velocity gameObject.GetComponentInChildren lt Camera gt ().transform.forward fireSpeed NetworkServer.Spawn(fb) And the code for the camera attached to the player void Update() mouseX Input.GetAxis("Mouse X") mouseSensitivity Time.deltaTime mouseY Input.GetAxis("Mouse Y") mouseSensitivity Time.deltaTime Horizontal Looking playerBody.Rotate(Vector3.up mouseX) Vertical Looking xRotation xRotation mouseY xRotation Mathf.Clamp(xRotation, 90f, 90f) transform.localRotation Quaternion.Euler(xRotation, 0f, 0f)


Unity Changing color of 2D sprite distorts sprite shape In my 2D game, my circle shape for example, appears round, but when I change the color then it turns into a low poly circle with 8 16 points, more like a potato. Is there any way around this? myColor new Color32 ((byte)colorR1, (byte)colorG2, (byte)colorB3, visibility) Color32 negativecolor new Color32 ((byte)colorR1, (byte)colorG2, (byte)colorB3, (byte)(255 visibility)) MaterialPropertyBlock props new MaterialPropertyBlock () props.SetColor (" Color", myColor) rend.SetPropertyBlock (props) props.SetColor (" Color", negativecolor) backchildrend.SetPropertyBlock (props)


How do I size my map in blender so it will be the right size in unity? I am working on a fps game but I cant get the size right of my map in blender, every time I export it to a .fbx file (unity won't work if it is a .blend file) it is a super small plane floor in unity the player controller is 10 as big as the map. I don't know what to do.


Speech recognition in Unity 5 for Android I've been working on a game in which the player have to say particular words to perform various tasks. For example, if the player says "boat", a boat pops up in the game. The game I'm building is specifically for offline play, on an Android device. Just for reference, there is a game titled "Pah!" which implemented this offline speech recognition for one specific word. In this game, when you say "pah", the GameObject moves jumps. I've tried everything from speech to text to forums, and even tried Google and used using Windows.Speech, but nothing works. From what I've learned, I need to use the Google speech API for Android speech recognition. I am a bit new, when it comes to Java. I gave it a try and created a basic script, which I thought might take at least one input in speech from the player, but Unity disagrees and says it couldn't recognize the script. I created another script in C , by taking help from tutorials, but when I switch the platform from Windows to Android it doesn't work, because Unity.Windows.Speech is a Windows namespace I am blank, and hence, this question. I have googled, visited forums, and even looked at YouTube videos for an answer. I came across a few Unity assets which I paid for, and they are all garbage. If anyone could help me, how do I implement speech recognition in Android, using Unity 5?


Line of sight shader Strategy games (such as Door Kickers) use a player's unit's line of sight as a major game feature. To provide feedback to the player regarding which areas are in view and which are not, different colours are used to display areas that are currently visible by a unit and areas which are not. Can anyone recommend an approach for creating this effect in a shader?


Unity NavMesh pathfinding using Job System I'm trying to write a system where I can run each enemy's NavMesh pathfinding in parallel, using Job System. The problem I'm having is that I can't pass the NavMesh agent argument as it's a reference type. InvalidOperationException PathfindJob.agent is not a value type. Job structs may not contain any reference types. I'm probably approaching this problem in a completely wrong way, but this is all I've come up with. Here's the current Enemy code using System.ComponentModel using Managers using Unity.Collections using Unity.Jobs using UnityEngine using UnityEngine.AI using UnityEngine.Jobs namespace Characters RequireComponent(typeof(Rigidbody)) public class Enemy MonoBehaviour Header("Stats"), SerializeField private int health 100 SerializeField private int damage 20 SerializeField private float aggroRadius 10f private Rigidbody body private NavMeshAgent agent private Transform target private void Awake() body GetComponent lt Rigidbody gt () agent GetComponent lt NavMeshAgent gt () target PlayerManager.GetInstance().GetPlayer() private void OnDrawGizmosSelected() Gizmos.color Color.blue Gizmos.DrawWireSphere(transform.position, aggroRadius) public struct PathfindJob IJobParallelForTransform public Vector3 TargetPosition public NavMeshAgent Agent public float AggroRadius public void Execute(int index, TransformAccess transform) var distance Vector3.Distance(TargetPosition, transform.position) if (distance lt AggroRadius) Agent.SetDestination(TargetPosition) I'm scheduling the job from the GameManager class.


How to code simple Goomba like AI for 3D Platformer? I'm making a 3D Platformer and have an enemy similar to a Goomba in terms of AI. How do I get the enemy to walk around and then follow the player when they're in range?


Why RaycastAll misses some objects? Update 2 (see below) I'm writing a turn based game. During setup phase time scale modifier equals to 0, what prevents running of any physics based code and FixedUpdates. User have freezed action and may make decisions. The problem is that sometimes I cannot select objects during the setup mode. I'm doing selection in the following way I obtain mouse position ray I run RaycastAll against this ray without limitations I check for hit objects, which has Selectable script on them. Then rest of the logic happens. Mouse handling looks like following Ray ray Camera.main.ScreenPointToRay(Input.mousePosition) (...) RaycastHit hits Physics.RaycastAll(ray) DEBUG string debug quot Raycast all gave quot hits.Length quot hits quot for (int i 0 i lt hits.Length i ) debug hits i .collider.gameObject.name quot quot Debug.Log(debug) END DEBUG Sometimes though I'm not getting valid results from RaycastAll. Take a look at the following example I clicked top left blue ship. You may see a small sphere on it I wrote a debug code, which generates a series of spheres along the ray to make sure, that it is valid. Since you see only one sphere here, it seems like everything's OK (note that I added this code to diagnose the problem. Spheres surely aren't causing it) The scene view looks like following It should be clear on this image, that ray hits the ship's box collider. In this specific case, a couple of units next to ship is an explosion, which has bigger sphere collider. You can also see debug log from the session, which clearly says, that RaycastAll only hit explosion and it missed the ship, which is just next to it. Now the question is why RaycastAll doesn't return the ship along with the explosion? Note, that this problem happens more often and without near objects with colliders, sometimes I just cannot select a ship and all I have to do is to move camera, such that object is closer to center of the screen. Edit Now this gets interesting! I added some debugging. After the RaycastAll, I manually go over all colliders in the scene and verify the raycast. The code now looks like following RaycastHit hits Physics.RaycastAll(ray) DEBUG string debug quot Raycast all gave quot hits.Length quot hits quot for (int i 0 i lt hits.Length i ) debug hits i .collider.gameObject.name quot quot Debug.Log(debug) var colliders GameObject.FindObjectsOfType lt Collider gt () foreach (var collider in colliders) RaycastHit temp if (collider.Raycast(ray, out temp, float.PositiveInfinity)) Debug.Log( quot Manually verified, that ray hits quot collider.gameObject.name) END DEBUG And when I try to click the quot un raycastable quot object, I get Raycast all gave 1 hits MissileExplosion(Clone) Manually verified, that ray hits MissileExplosion(Clone) Manually verified, that ray hits Falcon(Clone) A bug in Unity engine? Edit Yup, a bug in Unity engine. Hey, We have been able to reproduce this bug and have sent it for resolution with our developers. Regards, Unity QA


What's the best for doing ground check? What's the best for ground check? I have a capsule player and I'm using the raycast technique but it's not accurate when it comes to slopes. So what's better? Overlapping, Raycasting, CheckCapsule, or CapsuleCasting?


Why are the inputs not changing the animation on keypress? I have been following this tutorial. You can watch 16 00 18 20 to see what I am trying to do. What should be happening is I press a key, my animation plays and the parameters or Inputs get updated depending on which key I press. There are no errors in my script, but the parameters or Inputs are not updating. I have checked that I am using floats and that all my names match up. I've watched this part of the video and checked that my code was exactly like his multiple times. When using the model that he used in the video, the inputs the inputs are working fine. So would this mean there is something wrong with my animation, or is this an issue in my script? using UnityEngine using System.Collections public class Player MonoBehaviour public Animator anim private float inputH private float inputV Use this for initialization void Start() anim GetComponent lt Animator gt () Update is called once per frame void Update() if (Input.GetKeyDown("1")) anim.Play("Armature Walking", 1, 0f) if (Input.GetKeyDown("2")) anim.Play("Armature TurnRight", 1, 0f) if (Input.GetKeyDown("3")) anim.Play("Armature TurnLeft", 1, 0f) if (Input.GetMouseButtonDown(0)) int n Random.Range(0, 2) if (n 0) anim.Play("Armature Walking", 1, 0f) else anim.Play("Armature TurnRight", 1, 0f) inputH Input.GetAxis("Horizontal") inputV Input.GetAxis("Vertical") anim.SetFloat("inputH", inputH) anim.SetFloat("inputV", inputV) Anyone got any ideas?


Unity3d Do I need to destroy gameobject AND script? From proper leak protection do I need to delete both of these or will getting rid of one take care of both? Currently I am destroying the script AND the gameobject private void OnDestroy() Destroy(this.gameObject) Destroy(this)


Problem with coroutines unity 3d I cannot understand why the coroutines are not waiting the designated number of seconds before executing the code below it. At the moment, the animation bleeds into the next state. I could get around this by using .time and if statements but I thought the whole point of coroutines is that you can avoid that sort of mess. public IEnumerator LoadBow() this.gameObject.GetComponent lt Animation gt ().CrossFade("Load Bow") yield return new WaitForSeconds(this.gameObject.GetComponent lt Animation gt () "Load Bow" .length) aimStates AimStates.Draw public IEnumerator DrawBow() this.gameObject.GetComponent lt Animation gt ().CrossFade("Draw Bow") yield return new WaitForSeconds(this.gameObject.GetComponent lt Animation gt () "Draw Bow" .length) aimStates AimStates.Aim public void Aiming() moveTarget.SetActive(false) switch(aimStates) case AimStates.Load StartCoroutine(LoadBow()) break case AimStates.Draw StartCoroutine(DrawBow()) break


How to make AI detect a target behind a wall, who is only partially exposed? I'm making an FPS game where, even when a target's whole body is behind a wall or box, but its finger or foot exposed, the AI should be able to detect it and shoot its finger. So far the way I've thought of to implement this it so traverse all the targets, find who is near a wall, and compare their position with the corner of wall. But I don't know how to check whether its finger is exposed. I could use a raycast forward from the AI's gun, but would I need to add a collider to every small body part of every target?


Memory game texture on cards I'm new with Unity and I'm working on recreating memory game. I found this sample http xtasestudios.com unity samples (select "Memory"). I decided for C . I've created my own card in Blender, added 3 different materials (without textures), also I created flip flop animations. After importing .blend file in Unity and assigning scripts, textures, animations, positioning camera etc.. Everything works fine, except textures on cards. I can change color on cards, but when I want to see any texture on my card, I see only color, not whole texture. I really have no idea why is this happening and how to fix it. Any help will be appreciated!


What is the standard practice for animating motion move character or not move character? I've downloaded a bunch of (free) 3d warriors with animations. I've noticed for about 25 of them, the 'run' animation physically moves the character forward in the z direction. For the other 75 , the animation just loops with the characters feet moving etc., but does so in place, without changing the character's physical location. I could fix this by 1.) Manually updating the transform in code for this 75 , to physically move the character 2.) Alter the animation by re recording it, with a positive z value at the end (when I did this it caused the character to shift really far away the rest of the units, probably something to do with local space vs world space I haven't figured out yet). But before I go too far down this rabbit hole, I wonder if there is any kind of standard? In the general case, are 'run' 'walk' animations supposed to move the character themselves, or is it up to the coder to manually update the transform while the legs move and arms swing in place? Is one approach objectively better than the other, or maybe it depends on the use case? If so, what are the drawbacks of each? I know nothing about animation, so I don't want to break convention (if there is one).


Reverse Movie in Unity 5 guys! Is it possible to reverse video or apply a rewind in Unity 5? I searched in the web but could not find the solution.


Prevent showing movie files after packaging unreal game I developed a game which has some videos inside it. I added videos into my project folder so that I can access them. After packaging, on the folder all videos will be shown as its original format which everyone can play it. How is it possible on release version no one can go to game folder and play it? Maybe some kind of encryption or change format of file which only its game can play it would help it. For example when you have a game on your computer, the only way to see the video is that you play the game and you will see relevant videos in the right time. However, after packaging, all videos will be on a folder any everyone can go to the folder and play it and see videos even without playing game. In Unity after releasing the game, you can't access assets, it will be shown in a file with .resource extension so no one can access it. However, in Unreal Engine, it will show the real file.


ArgumentException The Object you want to instantiate is null I am trying to copy data over from a binary file but when trying to instantiate a gameobject, it comes out as "null". static void LoadBuildings(SaveBuilding buildings) if (buildings.Length 0) return foreach(SaveBuilding b in buildings) if(b.type.ToString() "Farm") Farm build Instantiate(Resources.Load("Farm")) as Farm Debug.Log("Build " build) build.position.x b.positionX build.position.y b.positionY build.level b.level build.levelText build.GetComponentInChildren lt Text gt () The debug line shows there is no object and when the next line tries to execute I get an error ArgumentException The Object you want to instantiate is null. I initially had it as Farm build Instantiate(build.prefab) as Farm as I get an error "Use of unassigned local variable". I tried adding a prorperty above the if statement "GameObject build", I tried doing Farm build new Farm() above the if statement also but still get the initial error. I have a folder titled "Resources" and confirmed a prefab labelled "Farm" is there also. Could it have anything to do with the "static" prefix for the method?


How to detect which car T boned the other in a collision? Setup The game has cars and collisions, and I'm trying to create the following system When a car T bones another, the one getting T boned is destroyed When the cars collide laterally (usually just bump into each other), a normal physics collision happens (and nothing is destroyed) When the cars collide head on, the lighter one is destroyed. The cars are all instantiated from 1 prefab. This can't be changed. Car Setup The main body sans the bumper has a normal, non trigger collider and the dynamic Rigidbody. It has the tag quot Destructible quot . A child object (which also houses the bumper model, but that shouldn't matter) has a normal, non trigger collider for the bumper. It has no Rigidbody and reports to the parent's Rigidbody. It has the tag quot Destroyer quot . Attempted Solutions 1) The transform.forward solution Get the transform.forwards of both cars and compute their dot product. If the 2 vectors are opposite each other (or close to it), destroy the lighter car. If the vectors are facing away from each other (or are close to parallel), let a normal collision happen. If the vectors are perpendicular (or somewhere in that ballpark)... then I'm lost. How do I know which car T boned which? That brings us to the solution 2. 2) The 'multiple colliders' solution Assign another collider to the bumper of the car and give it a separate tag (e.g. quot Destroyer). As a consequence, give the other main collider a tag, too (e.g. quot Destructible quot ). If a Destroyer collider hits a Destructible, the latter is destroyed. If a Destructible hits a Destructible, a normal physics collision happens. If a Destroyer hits a Destroyer, destroy the lighter one. But here, I run into an issue. You can't have multiple colliders on the same game object. Ergo, create an empty child and attach it there. I won't set it to Trigger, or otherwise it won't detect collisions with another of its type (i.e. Destroyer). In order to destroy colliding objects, I need a script and an OnCollisionEnter() inside it. OnCollisionEnter() won't run if neither of the game objects has a non kinematic Rigidbody. This means I need to give the bumper colliders a non kinematic Rigidbody. But if I give them dynamic Rigidbodies, they'll just... float away from the car. In other words, I need a way to create a 2nd collider but keep it firmly attached to the car. Furthermore, if the main collider covers it, then I need to exempt it from collisions with the 2nd collider (let's call it the sub collider), and I can't use layers to do that or otherwise the sub collider won't detect main colliders on other cars. If I don't cover it, then I need the sub collider to act as a normal physics collider, too, when it hits, for example, a wall, and not have the bumper sink into it. That means it needs a non kinematic Rigidbody. How can I solve this issue?


Unity RigidBody not rebounding as expected on low impact collisions I have a Rigidbody2D with a CircleCollider2D, on which I display a sprite of a circle. This Rigidbody can be "shot" in my game. I also have 4 rectangular BoxCollider2Ds on the edges of the game screen. When I shoot the circle, it rebounds fine from the rectangular colliders, except for cases when the impact velocity normal to the rectangular collider's surface is very small. In that case, the rebound velocity in that direction is somehow zero. Here is the circle's RigidBody2D and CircleCollider2D setup Here is the BoxCollider2D of the rectangular collider The material "New Physics Material 2D" attached to the ball and the BoxColliders has Friction set to 0 and bounciness set to 1 Here are two gifs, the first one demonstrating how it works (correctly) in most cases, and the second one demonstrating what happens on a low velocity impact. The "choppiness" of these gifs is due their "giffy" nature. In my game, the movement is smooth. I'm wondering why, on the low velocity impacts, the ball doesn't rebound in the same way as on the high velocity impacts (i.e, by the outbound angle inbound angle rule)? Edit I stepped into the circle's void OnCollisionEnter2D(Collision2D collision) method, and, sure enough, on the very slow collisions, the collision.otherRigidbody.velocity had a zero component for the slow velocity of the incoming collision (so depending on whether the impact's x or y velocity was slow, the respective component of the resulting velocity was, for whatever reason, set to 0). Oddly enough (at least for me I am still not completely familiar with all of Unity's in's and out's), the collision.relativeVelocity had been updated to hold the correct resulting velocity of the impact. Thus, by adding following code to the OnCollisionEnter2D method, I am able to handle the collision correctly, even on low impact collisions if (collision.otherRigidbody.velocity.x 0) collision.otherRigidbody.velocity new Vector2(collision.relativeVelocity.x, collision.otherRigidbody.velocity.y) if (collision.otherRigidbody.velocity.y 0) collision.otherRigidbody.velocity new Vector2(collision.otherRigidbody.velocity.x, collision.relativeVelocity.y) While this seems to solve the issue I am experiencing, it doesn't seem to me that I should need to be doing this...


Weird "jiggly" "warping" effect on my tiles I need help with a problem I'm having in Unity regarding a quot jiggly quot quot warping quot effect. It is a strange effect which occurs when I move my sprite character and makes the tiles have additional pixels which aren't on the sprite and disappear when you move more. I've also linked a video of my issue you can see it more clearly on the tree. To note My tiles are 16x16, my fox sprite is 64x64 and the enemy sprite is 48x48. I'm using Cinemachine.


Select a button without calling click i have a grid layout group containing buttons. My game must be playable with a joystick and so I have to navigate the buttons using horizontal vertical input. My problem right now is when the layout group first becomes visible. Once I click on a button (with my mouse), it becomes "selected" and I can navigate through the layout group with my keyboard and 'click' with spacebar. This functionality is all fine, except for the need to click the button with a mouse to set the first selection. I've tried both of the following void buttonClicked() Debug.Log("clicked") void Start () this button is actually instantiated from a prefab, not shown here Button btn inventorySlot.button btn.onClick.AddListener(buttonClicked) attempt 1 btn.Select() attempt 2 eventSystem.SetSelectedGameObject( btn.gameObject, new BaseEventData(eventSystem) ) both these commands do select the button, but they also inadvertently call the onClick, and the button is clearly being clicked because it changes color (I have configured this through button opts in the inspector). My question is how can I "select" the button without clicking it? I perhaps should also note, I am populating the layout group with buttons at runtime. Each button is intantiated from a prefab in Start() (not showing that here). I only add the event listeners and try to select the button after it's already added to actual game objects in my scene.


Waitforseconds is skipping over I have a function for a timer using waitforseconds but instead of waiting for how long I want to, it just skips it. A ui text should become "foo" then 5 seconds later become "bar" but it turns to bar as soon as it starts. Code void Update () text1.text "foo" wait (5) text1.text "bar" IEnumerator wait(int time) yield return new WaitForSeconds(time)


Unity3D Tag as a public variable in editor How do you incorporate Tag strings into a scripts editor found in the inspector? What it is I'm babbling about When you create a public GameObject fooObject in a script, it shows up as a box that can have Game Objects dragged onto in its editor. It also has a small clickable dot that shows every Game Object that could be selected. Now, say I have a public string fooString that would specifically be used for referencing the Tag strings of Game Objects (such as if (fooObject.tag fooTag) or another use). Is there a way to define that string so that in the script's editor it strictly allows tag names to be used with it? I'm assuming with a similar clickable dot or a drop down menu of every selectable tag. Although I could just manually type my string, a solution like the one above would have big object orientated advantages. For example, if I was to change the name of this tag, it would change the string variable accordingly, as if the variable was a reference to such tag. Note to the moderators I looked for an answer to this question for nearly 2 hours now to no avail. I understand that I may be missing some specific wrong word choice, in which case this question easily could have already been answered here. If this is closed as a duplicate, then, a quick comment explaining my mistake would be greatly appreciated.


Unable to save player data in a binary file within Update() method I'm trying to save player life within a binary file in Application.persistenceDataPath. I've written a method to store the player life public void SaveLife() BinaryFormatter bf new BinaryFormatter () FileStream file File.Open (Application.persistentDataPath " playerInfo.dat", FileMode.Open) PlayerData data new PlayerData () data.savedLife life bf.Serialize (file, data) file.Close () The problem is that when the SaveLife() is called OnApplicationQuit it works. Instead, if I call it within an Update() method of a class, it doesn't work. The Update() method is called when a certain event is triggered void Update() if (life lt 20) if ( certain event is triggered) SaveLife() lifeTimer Time.deltaTime if (lifeTimer lt 0) ResetLife () The container class for the data is Serializable class PlayerData public int savedLife What could be the problem?


How can I separate gameview from UI most efficiently in Unity? Let me provide an image to illustrate what I mean. It is from a game called Runescape.


How to generate a "loop room" in a platformer game (by Unity)? I want to build a level with a room whose left edge is linked to right edge in a 2D platformer game in Unity. My goal is let all objects disappear in one side will appear in other side of the room. Just like this Both sides should have collision with other objects. Right now I'm doing this by cloning objects on the other side, but it is too complicated. Is there any other good way to solve this?


Make the texture array node work with cubemaps? I am working on a procedural interior mapping shader in Unity's Shader Graph. Ideally, I'd like to feed it a set of cubemaps it can pick from semi randomly. However, it seems that by default the texture array asset one can provide to a graph does not support reading cubemaps. Does anyone have a way to use this, or perhaps a clever custom node or alternate texture mapping, so that I can read a number of cubemaps into the shader semi randomly? Preferably an arbitrary number, but even a fixed number would be somewhat of an improvement.


Unity5 UI How to trigger button click event while preventing menu item deselect event? So I've got a load menu using Unity's new UI system, basically just a list of save games you can select with a mouse click along with a couple of buttons at the bottom to delete or load the selected game file. I've been disabling the Load Game and Delete Game buttons using the interactable attribute whenever a saved game item in the list is deselected deleteButton LoadPanel.GetComponent lt Button gt ().interactable false loadButton LoadPanel.GetComponent lt Button gt ().interactable false This disables the buttons fine, but when I click on a saved game and then click a button, the deselect event for each save file is triggered BEFORE the onclick event for each button. This is no good. If I have no deselection event for each individual save file I can click on each save file and then click the load or delete buttons and every thing works fine, but the buttons never get disabled which is not ideal. My question is How can I disable the buttons when an item is deselected, but still trigger the onclick event when they are selected? Are there any workarounds to this?


Large Mesh at a far distance So I am trying to do something like KSP, where I have a ground to orbit Level of Detail with the planets. And from theirBuilding a new Universe Video I know they are using scaled space, and local space, where (as i assume) The whole planet is divided in smaller quads. This is all fine but from my understanding They are all still in the same unity scene and rendered( if they re not invisible( isn t that automatically decided by the cpu gpu?)). But now to my question. Even if such a Quad just has 16x16 Vertices, it s still up thousand if not millions of units away from the scene origin and you and the camera(I know there are two cameras for near and far) Wouldn t this quad produce a lot of lag and be really inefficient? Or is this not a problem for unity. Generally how far can I put things in unity? Please also note that I know about the the trick where they move everything back to the origin if the ship passes 6000 units, to reduce the jittering.


How to increase drag sensitivity while dragging distance is less than a certain value I built a inventory hotbar wheel for mobile controls. The wheel can be accessed if I put my finger on a specific quot hitbox quot on the right side of the screen and drag left. The result looks like this. I haven't added in item icons and such, but the black stain things are going to be the outlines of the items, and there will be item icons in the middle of them. As you can see, the larger, darker outline is the active item (the one that will be used equipped from the inventory). I have coded the script for the inventory so that the active item will be 3 slots away from the right side of the screen. This is the script public class Quick Acces Slider MonoBehaviour, IDragHandler, IPointerUpHandler, IPointerDownHandler public Image quickAccessSlider public Canvas canvas public float slotDistance public float slotPosition public float trueOffset public float offset public float canvasWidth public Vector2 originalPosition public Vector2 position public float slideDistance public float slideCap public float scrollSpeed Start is called before the first frame update void Start() canvasWidth canvas.GetComponent lt RectTransform gt ().rect.width public void OnPointerDown(PointerEventData drag) originalPosition drag.position slotPosition new float quickAccessSlider.transform.childCount slotDistance 1f (slotPosition.Length) offset trueOffset slotDistance for (int i 0 i lt slotPosition.Length i ) slotPosition i ((i slotDistance) (slotDistance 2)) offset if (quickAccessSlider.transform.GetChild(i).gameObject.activeInHierarchy) slideCap slotPosition i OnDrag(drag) public void OnDrag(PointerEventData drag) position originalPosition drag.position slideDistance Mathf.Clamp(((position.x canvasWidth) 2f), 0f, slideCap) for (int i 0 i lt slotPosition.Length i ) Scale active objects, change color, etc quickAccessSlider.rectTransform.anchoredPosition new Vector2(slideDistance quickAccessSlider.rectTransform.rect.width, quickAccessSlider.rectTransform.anchoredPosition.y) public void OnPointerUp(PointerEventData release) Array.Clear(slotPosition, 0, slotPosition.Length) originalPosition Vector2.zero position Vector2.zero slideDistance 0 The inventory slider is set up so that there is a rectangular panel, with the item slots as its children, and the pivot point of the panel is the right side of the screen, as such Essentially, right now, because I have the offset value which makes the active object the one that is 3 slots from the right side, I actually have to swipe a certain amount before I can get to the first active item. I want to make it so that the slider is more sensitive to drag while the slide distance is less than the offset value, so that I don't have to drag as mush to get to the active item. I also want the effect to work in the reverse scenario, where I am trying to stow the slider (dragging toward the right of the screen). I've tried a few methods such as where I tweak the slideDistance while it is less than the offset, or where I try to Lerp the slideDistance value to the offset value, but none of them seem to work due to a few reasons. The main reasons my solutions didn't work was because the slideDistance value needs to be equal to the offset value once I'm done tweaking the value it is not longer less than the offset value to prevent jittery movement, and because I need the increased sensitivity to work both ways, when dragging left and also dragging right.


Unity sprite rig affecting performance I created a simple sprite rig using the skinning editor provided by the new 2D Animation V2 package. But it causes a huge FPS drop when added to the scene. Methods such as SpriteSkin.LateUpdate generates significant amount of garbage as shown in the picture See the spike shown on the CPU profiler when the rig is being enabled The rig is not even animated. I also checked the other sample rigs provided by Unity and they also performed in a similar fashion. Is this normal? I'm targeting mobile, so anything that can be done to avoid or improve the situation will be helpful. I'm using 2d animation v2 2.0.0 preview.2 in Unity 2018.3.8f


unity Tilt Android Device player Freeze When Die I attached tilt script to my Player to move player x and y Axis. Player have Rigidbody2D and also IsKinematic true. but the problem when the player can Die i want to stop tilting and player goes down to ground. here is my tilt Code public float Speed 20f void Update () if (PlayerControll.instance.isAlive) transform.Translate (Input.acceleration.x Speed Time.deltaTime, Input.acceleration.y Speed Time.deltaTime, 0) else PlayerControll.instance.PlayerRigidbody.isKinematic false I try to do that using disable tilt script when Player die and Iskinematic false but the problem is player can freeze to his position not goes down to the ground. I do that so many way but not done so what i do don't know then i post the Question. thanks in advance.


Game states passing data between scenes I'm not entirely sure if I'm doing this right, but I always considered the scene system in Unity as some sort of state management (rather than e.g. a level system) which allows to group the contents (entities, components) into the usual main states of the game (menu, ingame), which can then be invoked or replaced together. Now I have a very specific concern and I have no clue how to deal with that in Unity, mostly because of it's abstractions from code and other restrictions My game features a procedurally generate terrain where as I'd like to tweak the generator before actually launching it. The tweaking is done in some sort of 'pre game' state (as part of the main menu) where the values are stored in e.g. TerrainData model class. Usually in other engines, I'd to it like this Providing an UI within the menu state to tweak the parameters of the game Storing the parameters in a view model (and data model) Instantiate the ingame state (which requires said data model in the .ctor Pass the data model to a generator and start the generation Now, here are the main problems Most types in unity (scenes, monobehaviors) do not allow constructors because they use it for themselves It doesn't seem possible to instantiate scenes manually (there's only e.g. Application.LoadLevel("") which only takes the name of the scene, not a instance reference etc. it doesn't seem possible to pass data between scenes, without reverting to awkward workarounds such as singletons, playerprefs, DontDestroy etc. which are all not really suitable for this case. So, how can I properly solve this? Is there a better way to manage states rather than scenes? Prefabs maybe? Backlink to UntityAnswers question http answers.unity3d.com questions 1149480 game state management and passing data between sce.html


Prevent Unity from crashing your computer? Recently, I made a very dumb mistake that caused Unity to crash my computer. I could move the mouse sometimes, but everything else became completely unresponsive, leading to me having to shut off my PC. What happened I had an object, let's say an arrow, that could collide with another object, let's call it spawner. When the arrow collides with the spawner, it's supposed to destroy the arrow that activated the spawner. The spawner would then, as the name might imply, spawn more arrows. The problem was that I forgot to temporarily disable to collision on the newly spawned arrows, meaning that as soon as they would spawn inside the spawner's collision box, they'd spawn more arrows, and those arrows would spawn more arrows, and those arrows would... you get the idea. It was a very stupid mistake I realized the moment I hit play, but it was too late. Now, I know that was entirely my fault, but I was wondering if you could prevent Unity from sending your PC into a coma like that? (Besides not making a dumb mistake like that, of course...) I'll be honest, I kind of expected Unity would have some sort of fail safe for this kind of error. Is there a way to limit the object count for example?


How is entering cover animation done for cover system? I am trying to create a cover system for my 3rd person shooter game in Unity. My implementation is a basic one On Player enter Trigger Player move to preset cover position Player play Enter Cover animation (eg dash to cover) This is fine without root motion enabled, when it is enabled (so the movements look natural), instead of dash amp stop behind the cover, the Player will dash and stuck himself inside the cover (due to root motion). So I am curious, what is a good way to do the animation for cover system?


Mesh does not translate accordingly to WheelCollider So I am trying to implement a car controller script in Unity were the WheelTransform position and rotation is set with every update as the same as the WheelCollider position and rotation, it all works fine except for one thing when translating the WheelTransform, if the car goes slowly, WheelTransform translates as expected, but when the car goes faster, there's a clear offset between the WheelTransform position and the actual position of WheelCollider. Here's the code were WheelTransform position and rotation is set as the same as the WheelCollider position and rotation private void UpdateWheels() UpdateWheelPos(frontLeftWheelCollider, frontLeftWheelTransform) UpdateWheelPos(frontRightWheelCollider, frontRightWheelTransform) UpdateWheelPos(rearLeftWheelCollider, rearLeftWheelTransform) UpdateWheelPos(rearRightWheelCollider, rearRightWheelTransform) private void UpdateWheelPos(WheelCollider wheelCollider, Transform trans) Vector3 pos Quaternion rot wheelCollider.GetWorldPose(out pos, out rot) trans.rotation rot trans.position pos Every single one of the car controller scripts I've found and tried use the same code for this section, I have also tried with 2d sprites without any colliders as WheelTransform but neither the scripts or changing WheelTransform solved the problem. Thanks in advance for the help.


How to move a cube withour rolling it? I am trying to move a cube with my keyboard on a plane surface. However, the cube always rolling instead of moving. How could I slide the cube on the plane? What I have done I added a plane game object with a mesh colider I added a 3D cube object with a box colider and rigidbody I appended a ControllerScript to the cube ControllerScript private const float Speed 10 private Rigidbody rb void Start() this.rb GetComponent lt Rigidbody gt () void FixedUpdate() var x Input.GetAxis("Horizontal") var z Input.GetAxis("Vertical") this.rb.AddForce(Speed x, 0, Speed z) It looks like the AddForce method upset the cube. I already tried to reduce the friction of the plane and the cube, but this only delays the problem. How could I move the cube without rolling it? Whats the common way to do it?


Touch input not working well for mobile game made with Unity 2D I made a simple game in unity where the user taps their phone screen and the player jumps up. When I test it on my phone (not sure if this matters but it's a Samsung s9 ), I tap the screen and usually the tap causes the player to jump up and fall back to the platform properly, but sometimes when I tap the screen nothing happens at all it just stays in place. The game on my phones is also very slightly laggy (although, on my computer it runs smoothly) and I'm not sure how to fix that either or if they're related. This is the code attached to the player void FixedUpdate() Jump() Dead() void Jump() if (Input.touchCount gt 0 amp amp isGrounded) gameObject.GetComponent lt Rigidbody2D gt ().AddForce(new Vector2(0f, jumpForce Time.fixedDeltaTime), ForceMode2D.Impulse) Also, I know that it's the touch input that's the problem, because when I make it so that pressing the up arrow key on the keyboard makes the player jump, it works perfectly fine. If there's some other information about the game you'd need to know to answer my question, let me know. Thanks for your help.


Make a flying object rotate so the camera sees the rotation When I attach a camera to my flying object (plane), when I rotate the object, the camera is perfectly following it so you can't really "feel" the plane rotating. I want to create the effect that you see in flying games where you see the plane rotating along the x axis (so you see the nose go up and tail down) while also semi following the plane, creating a better effect. How do I achieve this?


Attach movement to each list object How would i move every sphere that gets spawned every 2 seconds ? Basically i want every sphere to follow the previous spawned sphere or even all N 1 spheres should follow the first spawned sphere along a predefined path and they should keep rolling as a train of spheres. I am lost when i try to imprint movement to each sphere. using System.Collections using System.Collections.Generic using UnityEngine public class Spawner MonoBehaviour public GameObject prefabs public List lt GameObject gt listBalls new List lt GameObject gt () private GameObject x public int timer 0 private float movementSpeed 5f void Start() createBall() void Update() if (Time.time timer gt 0.8f) createBall() timer 2 listBalls listBalls.Count 1 .transform.position new Vector3(0, 0, movementSpeed Time.deltaTime) void createBall() x prefabs Random.Range(0, prefabs.Length) Instantiate(x, x.transform.position, Quaternion.identity) listBalls.Add(x) void moveBall(GameObject x, GameObject y) x.transform.position y.transform.position new Vector3(0,0, 1) Loop added but movement staggered void Update() if (Time.time timer gt 0.8f) createBall() timer 2 foreach (GameObject item in listBalls) item.transform.position new Vector3(0, 0, movementSpeed Time.deltaTime)


Player animating the wrong direction once he is rotated I have used the scripting root motion move the player when using an 'inplace' animation. All works correctly until the players rotation is off 0,0,0. This is expected as the movement is along the transform.z axis but how can I account for the rotation in the script and apply it so the movement is correct in game? The gorillacontroller script is the script we are trying to fix On playerGorilla. animator is on the playergorilla. The gorilla1 is the gameobject holding the mesh and the bones for the character. I will also add the transforms are moving this was my silly mistake because I had tool handles in global instead of local. This makes it even more confusing however because all tranform.z (blue axis) are facing the correct way for the animation to work but the animation is only ever playing in the original direction where the rotation is 0,0,0,0. using UnityEngine using System.Collections RequireComponent(typeof(Animator)) public class RootMotionScript MonoBehaviour void OnAnimatorMove() Animator animator GetComponent lt Animator gt () if (animator) Vector3 newPosition transform.position newPosition.z animator.GetFloat("Runspeed") Time.deltaTime transform.position newPosition


Frame Dependency vs Time Dependency Just today, I was dealing with this very topic in class, and I had a hard time following through the lectures. Could someone explain to me what it means for something to be frame dependent, in layman's terms? As far as I know, it's not Unity specific. I suppose this applies to every game, regardless of its engine. An elaborate answer would do really good for me, as I'm a student, and I'm gonna be doing projects on this. Thanks!


A Pathfiding movement is not stopping and constant I'm trying to make my player move towards mouse click using A Pathfinding but I'm having some odd issues that I can't solve. One of the issues is that player is moving a little bit even though it arrives at the position of the other transform The second one is that the force is that is applied to the player is not constant, I would like it to keep always the same movement speed. I've tried to change to use transform.Translate to move the player with constant movement speed but it makes the movement to be like walk a little then stop, walk a little then stop... This is the code that I'm using using System using System.Collections using System.Collections.Generic using Pathfinding using UnityEngine using UnityEngine.UI public class Player MonoBehaviour SerializeField private float speed 100 SerializeField private Text lifeText SerializeField private int life SerializeField private GameObject target SerializeField private float nextWaypointDistance 3f AI configurations private Path path private Rigidbody2D rigidbody private Seeker seeker private int currentWaypoint 0 private bool reachedEndOfPath false Start is called before the first frame update void Start() seeker GetComponent lt Seeker gt () rigidbody GetComponent lt Rigidbody2D gt () InvokeRepeating( quot UpdatePath quot , 0f, .2f) Update is called once per frame void Update() lifeText.text quot Vida quot life.ToString() if (Input.GetMouseButtonDown(1)) right click Vector2 mousePos Input.mousePosition Vector2 worldPos Camera.main.ScreenToWorldPoint(mousePos) target.transform.position worldPos private void UpdatePath() if (seeker.IsDone()) seeker.StartPath(rigidbody.position, target.transform.position, OnPathComplete) void FixedUpdate() if (path null) return if (currentWaypoint gt path.vectorPath.Count) reachedEndOfPath true return else reachedEndOfPath false Vector3 direction (path.vectorPath currentWaypoint (Vector3)rigidbody.position).normalized Vector3 force direction speed Time.deltaTime rigidbody.AddForce(force) float distance Vector2.Distance(rigidbody.position, path.vectorPath currentWaypoint ) if (distance lt nextWaypointDistance) currentWaypoint private void OnPathComplete(Path p) if (!p.error) path p currentWaypoint 0 What I want to is to make the movement smoother and with constant movement speed. Can you guys help me?


Convert coroutine into void I want to get rid of a co routine and do this with a void. How could I convert his IEnumerator into a void? private IEnumerator pChangeFoV() float zValue 70f for (float t 0f t lt FoVDuration t Time.deltaTime) float fNew Mathf.Lerp( camera.fieldOfView, zValue, t FoVDuration) camera.fieldOfView fNew yield return 0 camera.fieldOfView zValue Thank you for the help!


How to import Blender mesh rig separately from animations for generic rigs in Unity? Currently I'm creating mesh, rig and animations in Blender and export them together as an fbx file. I know that importing animations separately works for humanoid meshes, but how to do this for a generic rig? Why? After importing a character, I have to add components to some bone game objects of the characters rig. Adding or changing animations of an already existing character currently requires me to reimport mesh rig aswell as the animations and then add the components to those game objects again. Also sometimes the reference of existing prefabs to the reimported mesh is lost and I have to add the mesh to those prefabs again, this might have been me doing somethin wrong though. Better solution? I also thought about naming bones in blender in a certain way and have a script in Unity add these components, I would still prefer to import animations separately though. Thank you in advance!


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!


Instantiation of multiple objects with varying velocities I am looking to multiple objects of the same prefab at the same time with varying velocities. public GameObject prefab public float xDirection public float yDirection void Update () GameObject prefab1 Instantiate (prefab,transform.position,quaternarion.identity) as GameObject GetComponent lt RigidBody2D gt ().velocity new Vector2 (xDirection,yDirection) I want to create three instances at once, but have the x y direction be different. I am looking at creating an instance at three separate velocities. I know I can do something like this using void Update () if (Input.GetKey(KeyCode.space)) xDirection 1f yDirection 1f shootObject() xDirection 2f yDirection 2f shootObject() xDirection 2f yDirection 2f shootObject() void shootObject () GameObject prefab1 Instantiate (prefab,transform.position,quaternarion.identity) as GameObject GetComponent lt RigidBody2D gt ().velocity new Vector2 (xDirection,yDirection) but I feel like there is something else that I should be able to do to simplify this even further since this seems to be very messy code. (I apologize if something seems a little odd. Have only been coding for around a few weeks.) Thank you for the help!


Unity raycast equivalent in Unreal I've been moving from Unity to Unreal and I'm finding it difficult to grasp the Raycast (Trace) logic of Unreal. The use case I'm trying to implement at the moment is to trace a ray and check if I hit a specific set of objects or if there are other objects blocking the line of sight. In Unity, I would use Raycast, define a new specific Layer, set the object layer to it, create a LayerMask with that Layer and Raycast. I consider this method to be performant as the use of layer masks provide a form of optimization and most importantly I'm guaranteed that if the ray hits an object than it's because its layer is part of the layer mask and if I'm using multiple layers I could simply check which layer the hit object has. In Unreal it's been harder to understand what are the solutions that offer better performance and are easier to use. The C documentation for Line Trace (channel or object type) is very poor when comparing to Unity's. Can anyone shed some light on how to move from the Unity logic to Unreal using the above use case as an example?


My script isn't deleting or destroying my prefab game object in Unity2D My script isn't deleting this game object once it reaches a certain position in my game. This is my script public float left public GameObject enemyLeft void Start () enemyLeft GameObject.Find("Enemy Left") void Update() if (transform.position.x lt left) Destroy (enemyLeft) enemyLeft is a prefab gameObject that is being spawned in by my spawner. This is the script where I intend to Destroy the game object public float left public GameObject enemiesLeft void Update() for (int i 0 i lt enemiesLeft.Length i ) if (enemiesLeft i .transform.position.x lt left) Destroy (enemiesLeft i ) Why isn't it deleting the game object?


Why is Unity3D on OSX ignoring my XBox 360 controller? I'm using a fork of the Tattie Bogle driver that has a signed kext. The System Settings panel shows all inputs correctly. One axis is configured in Unity3D 5 like this Still, I don't see any input when the game is running. I also cannot configure Positive Negative Buttons for any input in the Input Manager panel clicking the input line edit and entering a keyboard key works fine, but pressing a controller button does nothing. What am I missing here?


How to make player instantly move to the right or left when entering a box collider I have a box collider and right now when I walk into it it says "you can't go there yet" I would like it for it to also move the player like 3 steps to the right or something. How would I do thatr?


Unity3d mesh is getting distorted while animation I attached boxing glove to rig using this method https stackoverflow.com questions 34719718 transferring rig weights from one mesh to another in blender 2 76 It works fine in the blender, But while animating in unity mesh is getting distorted. Image https imgur.com a 5McCX Anyone knows how to fix this?


Unity3d iOS unable to find iPhone GlesSupport.h i've an old unity project and i've tried it just today (with unity 4.1) and xcode 4.6. Xcode is unable to build it for the error "iPhone GlesSupport.h" file not found. Im pretty a noob under xcode and objective c in general so i've searched in internet about this problem, but without any luck. Anyone know more or have experienced this problem? Thanks


Declaring Keycodes as strings How do I declare the keycodes as strings instead of selecting the keys from a list? Such that the user can input a key in inspector window and it will be read? public string StringKey quot a quot void Update () if (Input.GetKeyDown (KeyCode.StringKey))


Hold and swipe can't work together I Have a character in my game that must go when player hold finger at the screen, but when I swipe character first go, and then do swipe. (for example jumping character first go, and only then jump). This my code for touch if (Input.touchCount gt 0) Touch touch Input.GetTouch(0) if (touch.phase TouchPhase.Began) startTime Time.time startPos touch.position else if (touch.phase TouchPhase.Ended) endTime Time.time endPos touch.position swipeDist (endPos startPos).magnitude swipeTime endTime startTime if (swipeTime lt maxTime amp amp swipeDist gt minSwipeDist) swipe() else if (touch.phase TouchPhase.Stationary amp amp isTap 0) hold() This my code for a hold void hold() moveVelocity 3f And for swipe void swipe() Vector2 distance endPos startPos if (Mathf.Abs(distance.x) gt Mathf.Abs(distance.y)) if (distance.x gt 0) Debug.Log("Right swipe") if (distance.x lt 0) Debug.Log("Left swipe") if (Mathf.Abs(distance.x) lt Mathf.Abs(distance.y)) if (distance.y gt 0) Debug.Log("Up swipe") if (distance.y lt 0) Debug.Log("Down swipe") My question is When player swipe left character first go, and only then do swipe left. I want player swipe, without going forward. How can I do this?


Animation doesn't play in one state I have created an Animator and two sprite based Animations. Both Animations preview correctly. In the Animator, I have created two states and two transitions between them based on a Boolean parameter. In the GameObject's script, the Boolean value is set based on distance to the player. When the player is far away Animation A plays and when the player is close Animation B plays. However, while the transition from Animation A to B happens correctly when the player gets close, I only see the first frame of Animation B and it doesn't animate. If while in Play mode I preview Animation B (using the Animation window controls), it animates correctly. Meanwhile, Animation A always plays correctly when it is supposed to. What could cause this behavior? How can I get Animation B to play during runtime and not just when previewing? What's going on? Edit Some screenshots. quot Saw slow quot is quot Animation A quot above, and quot Saw fast quot is quot Animation B quot . Animator Animator State Slow Animator State Fast Transition slow to fast Transition fast to slow Animation Slow Animation Fast The code is very simple bool trigger playerDistanceSqr lt (activeDistance activeDistance) animator.SetBool( quot IsFast quot , trigger)


Keep a rigidbody velocity constant I have a "board" with a ball (rigidbody) moving over it and colliding with obstacles. I want its velocity magnitude to remain constant throughout time. How do I achieve this? What I've tried achieved so far My first guess was to use OnCollisionExit to set the velocity manually, but that lead to weird physics. I don't see how to use AddForce to do this since the previous movement would still be factored. To be clear, what i want is to set the velocity at all times to rigidbody.velocity.normalized x magnitude, where magnitude is a float I set previously. This would allow the physics engine to make all impact math to decide the direction of the ball after the collision, but my math would keep the velocity intact. I then decided to add UpdatedFixed and on every call set the velocity as stated above. It's working, but feels like a bad hack because I'm updating the velocity every frame and forsaking the physics engine.


How do I rotate the Camera around the player by Keypress in Unity? I want to rotate the camera around the player by pressing E and Q but it doesnt rotates around the player. I tried RotateAround but didnt worked. Code public Transform player public float smoothSpeed 0.125f public float rotateSpeed public Vector3 offset private Vector3 velocity Vector3.zero void LateUpdate () transform.position Vector3.SmoothDamp(transform.position, player.position offset, ref velocity, smoothSpeed Time.deltaTime) void Update() if(Input.GetKey (KeyCode.E)) transform.RotateAround(player.position, Vector3.up, rotateSpeed Time.deltaTime) if(Input.GetKey (KeyCode.Q)) transform.RotateAround(player.position, Vector3.up, rotateSpeed Time.deltaTime)


Bounce ball after collision I added Box Collisions (Walls) outside of the screen and a player (ball) with rigidbody and Circle Collider in dynamic forcing to a random direction. I want the ball to bounce when it collides the wall. Bomb.cs private Rigidbody2D rigidbody private Vector2 direction Use this for initialization void Start () rigidbody gameObject.GetComponent lt Rigidbody2D gt () direction new Vector2 (Random.value, Random.value) Update is called once per frame void FixedUpdate () rigidbody.AddForce (direction)


Getting world space vertex coordinates in Unity I'd like to get world space coordinates for a specific mesh vertex. Transform.TransformPoint() seems to be what I need however I'm unable to get the correct position. In the scene I have an object called "head" at Pos (0, 0, 0) Scale (0.03, 0.03, 0.03) and I'm trying to get the position of vertex id 590 in order to spawn another object at that specific location. Mesh mesh GameObject.Find ("head").GetComponent lt MeshFilter gt ().mesh Vector3 vertices mesh.vertices Vector3 newPos transform.TransformPoint (vertices 590 ) Debug.Log (newPos) The value of newPos is not on the head object.


Why does Unity require an EventSystem component for input during a play test, where input works fine without it in a build? Please be aware that this was initially a question about how to get the input to work. A comment pointed me in the direction of a fix, but only left me with more questions in regards to understanding the problem I was originally having, so I have edited my question to include the initial solution and focus on the question I still have. The Problem Recently, I have moved from using GUIText and GUITexture objects to using the Canvas to display UI elements. In effort to set up a prototype, some external GUI elements were imported, and when the game is built and run from my phone, everything works as intended. However, if I simply run the game from inside Unity, input is completely ignored. I originally thought this may have been a response to grabbing touch screen input, and expecting it to work on a regular screen with mouse input, but I have since confirmed that it still does not work when using Unity Remote to test the game on my phone. It has since been pointed out that I was not using an EventSystem, along side my Event Trigger objects. After implementing an EventSystem component, and the default input module supplied by the EventSystem interface, the input works. However, this still leaves me confused. What is the point of enforcing the implementation of the EventSystem, if it only ensures functionality during play test? Why would I want this system in my end build, when I can confirm that the build version functions properly, without it? Below you will find my setup, contextual to the problem. Click for a zoomed in view, as I have included the component structure of my UICanvas and MainCamera objects, in case it is helpful. In this case, we have a button that increases the max speed, when pressed. Everything works in a build, but nothing works during a play test. Additional Information I have enabled 'show touch input' on my phone, to confirm that the phone is still registering touch input. I moved to using the Canvas object after the 'depreciated warning' for using GUIText and GUITexture turned into a 'depreciated error'. Even if there is a suitable way to still perform these actions with the GUIText and GUITexture objects, I still wish to persist with using the Canvas. I am also personally curious as to why this issue exists within the Canvas, as it seems lead to obvious cases of severe inefficiency, in a system that seems to have been put together with the sole point of being more efficient. I can create manual OnMouseDown buttons that will work during play test, however, some GUI elements are more complex and persisting with this sort of solution seems like an incredible waste of time. As previously mentioned, I do not have any input issues if I simply build and run the game from my phone. However, this takes considerably more time than a simply debug test, and even without the high efficiency cost, I do not have access inspector manipulation during my play test. I am using Unity version 5.3.5 personal. Any solution that does not include updating Unity will be well preferred. While I have no physical problems updating Unity, in some previous projects updating Unity versions has lead to massive issues that we would prefer to outright avoid, if possible. TL DR Unity will not accept input on my input canvas during debug. I literally have to build and run my project each time I want to test input, or create dodgy hacks to provide input from the Inspector. The addition of an EventSystem allows input during debug play testing, but is not needed for input post build. Why does Unity act this way, and why do I need an EventSystem entirely for play test input?


Outputting Unity commandline build log to console? I'm using Blue Ocean to do a Unity3D build through command lines (https docs.unity3d.com Manual CommandLineArguments.html). I currently have a stage in blue ocean which runs the build command in a 'Windows Batch Script' outputting the log to a text file on the computer. is there a way to also output that same logging text to the blue ocean build output? Right now all I see is the batch command. One way to accomplish this would be if the build output was sent to the console instead of just the logfile passed in the argument.


Is there a way to check android version running the game using Unity3D? I want to separate code to run only on android 4.4 or higher. If it's lower, I do not want to run this code. What should I do?


Hide back button bar of android mobile while playing game I just want to hide back button bar of android mobile while playing the game. I tried to make it close by pressing back button,it getting close but its always visible. please help..


Kinect for Xbox One ( adapter) and Windows 10 Can I use Kinect Xbox One (with adapter like Kinect for Windows V2 device), SDK 2.0, to build applications on Windows 10? I've read the requirements for Kinect and it lists only Win 8.0 and Win 8.1. I'd like to use Kinect Xbox One device with Unity 3D and Hololens. Before I buy the device I'd appreciate if anyone can share some experiance or at least to confirm that would be possible to develop apps with Kinect for Xbox One on Win10? Many thanks.


In Unity, how do I move my character to an object when I click on it? Basic question here, and I feel like I'm close but can't quite get it. I have an object it's a pot on a stove that is in my 2D game. There will be multiple pots that appear and disappear in the game, all in predefined places (like on top of the burners of a stovetop). There's also a chef in the game, who goes to each pot and does an action. The user never directly controls the chef's movement instead, when the user clicks a pot, the chef runs over to the counter in front of that pot, where he can perform an action on the pot. Can someone tell me how to do this? I'm not only looking for the code but for a "correct" design, in terms of where the various variables and methods should be located. In other words, what goes in the pot's script and what goes in the chef's script? (I'm using C .) My thought was that the pot GameObject would have an OnMouseDown() method, to catch the user clicking on it. And in that method, there should be a call to a Move() method that is attached to the chef GameObject. But what I have is not quite working. The chef moves one small bit toward the pot but then stops. I realize that this is because I'm calling the Move function once and that's it it seems like the Update method should be involved somehow (the pot's or the chef's?) or maybe I should have an if statement in my Move method that checks to see if the user is at the pot, and if not, runs the move code in a loop. Or maybe the design is just fundamentally wrong and it could be done more easily. Here is the code I have public class PotController MonoBehaviour private GameObject chefObject void Start () chefObject GameObject.Find ("Chef") void OnMouseDown() ChefController chefScript chefObject.GetComponent lt ChefController gt () chefScript.Move () public class ChefController MonoBehaviour public float moveSpeed private Vector3 moveDirection public void Move () Vector3 currentPosition transform.position if (Input.GetButton ("Fire1")) Vector3 moveToward Camera.main.ScreenToWorldPoint (Input.mousePosition) moveDirection moveToward currentPosition moveDirection.z 0 moveDirection.Normalize () Vector3 target moveDirection moveSpeed currentPosition transform.position Vector3.Lerp( currentPosition, target, Time.deltaTime )


How to create a forest game scene in unity3d? I am pretty new to game development. I have started using unity3d. I have created simple games for which I have used plane (3d gameObject). Now, I want to move a step forward I want to create a forest with mountain and trees. So, I went through few tutorials and concluded terrain (3d Object) will be best fit. Issue My player falls down from the terrain due to gravity and if i disable gravity then my player flies up in y axes when moved over mountains. What is the way i can create terrain with gravity and so that my player doesn't fall from the terrain. Can anyone throw light on how do overcome above mentioned issue.


How should I deal with different enemy types? I'm making simple space shooter game for Android in Unity. I want to have different types of enemies (different weapon, stats, movement schemes) and I'm not sure how to do it. I'm quite new to objective programming and I don't really know what classes should I create. I guess I could just make a prefab for every enemy since there won't be many types, but that is not what I'm looking for. I have some ideas First of all I'd write an BaseEnemy class and enemy type subclasses that inherit from it. My first idea is to create those without MonoBehaviour. Then I'd have to make an EnemyScript with MonoBehaviour that I'd add to enemy game object. It'd have a specific subclass object inside, which will set every variable. BaseEnemy would just have undeclared variables and in subclass I'd set particular values. But I'm not sure how to deal with different movement schemes then. I wouldn't be able to put move() function in subclass since it wouldn't have MonoBehaviour, so I'd have to find another way. I might put in EnemyScript every possible scheme and then use correct one depending on some type value, but it doesn't seem like a proper way, does it? The second idea is to just make a MonoBehaviour BaseEnemy class. Then while creating enemy game object I'd just add correct subclass script (aaand... I'm not sure how to do it ) Could you tell me which one is a better way? Maybe neither of those?


Initializing Variables, Difference between Awake and in class initialization public class ExampleClass MonoBehaviour int exampleVariable 0 int exampleVariableForAwake void Awake() exampleVariableForAwake 0 What is the difference between initializing a variable at declaration vs. initilize in Awake? Which I understand is to be used in place of constructors in Unity C , welcome to correct me if I'm wrong. Which usage is considered a proper convention by the community, if any? Same question might also be in order for Properties, so I'll leave that open ended.


unity onCollisionEnter does not work I know this question has been asked several times but none of the answers solved my problem. I made an sphere and gave it rigidbody. then I draged the sphere on to a new made prefab. on mouse click Instances of this prefab are made and shot. the spheres collide with things in the scene but the onCollisionEnter function is not called. all things in the scene have colliders. I would be grateful if you could tell me what's wrong edited it works if either the sphere or the other object's collider is trigger and I use onTriggerEnter.


Why when destroying objects when quitting the game it's destroying the objects only in hierarchy? In one script i did using System.Collections using System.Collections.Generic using UnityEngine public class GameManager MonoBehaviour public LevelGenerator levelGenerator Use this for initialization void Start () Update is called once per frame void Update () private void OnApplicationQuit() levelGenerator.DestroyNodes() Then in the other script public void DestroyNodes() GameObject nodes UnityEngine.GameObject.FindGameObjectsWithTag("Node") if (nodes.Length 0) Debug.Log("No nodes to destroy found") else for (int i 0 i lt nodes.Length i ) DestroyImmediate(nodes i ) But the Nodes still exist in the Hierarchy and in the Game and Scene views. I used a breakpoint it's getting to the OnApplicationQuit And it's getting to the line DestroyImmediate(nodes i ) There are 100 objects and it's doing the line for each object. But then when i make continue they are still exist. I want that when i quit the game stop the play all the gameobjects to be destroyed.


Unity Create terrain in Blender? I am going to make a terrain ( not too big ) for my RTS and I was wondering whether to use Unity's terrain tool or create a terrain in Blender and import it to Unity?..I have been told that Unity's terrain is intense work for the mobile GPU..So would it be any good to make the terrain in Blender ( in terms of performance )?


How to convert game object world position to hex grid cell coordinates? I have a hex grid and a game object, let's say it's the player. What I want to do is know on which cell the player is on based on his world position, this would be easy on a simple grid but on a hex grid it's giving me a headache.


Screen Capture rendered on a RenderTexture in Unity I have a pretty wild idea for a unity application that would work on a multi display setup. The app would be running in full screen mode on one of my displays, and the contents of the remaining two displays should be rendered in game on a texture. I've seen RTMP clients for unity and I've tried streaming my desktop with OBS to a local RTMP server but the delay was too big (more than 5 seconds). I would prefer an instant (or very low delay) solution for mirroring my displays on textures in Unity. If anyone can help me solve this, i would appreciate it!


Unity won't slice images properly Okay, so I am very new to Game Development and I imported a .png file(made in Paint) to the assets and that file contains just a circle and an oval, not touching and far apart from each other, both of them coloured blue. When I open the sprite editor and click on splice, then select Automatic and Delete existing options and then click slice, I do not get different sprites, one containing the circle and the other containing the oval. The image isn't sliced at all. I have also set the sprite mode to Multiple, but to no avail. Can someone help me and tell me what I am doing wrong? The engine I am using is Unity. This is the image.


GameObject that should have a fixed speed keeps accelerating I'm using a coroutine to make a GameObject move from a random point A to a random point B. The GameObject should move along this trajectory at fixed intervals and at a constant speed. However, each time my coroutine that executes the movement is called, the GameObject is a little bit faster. private IEnumerator movement () Initialize position and rotation float distanceX endTransform.position.x startTransform.position.x float distanceZ endTransform.position.z startTransform.position.z float angleAroundY 90.0f Mathf.Rad2Deg (Mathf.Atan2 (distanceZ, distanceX)) this.gameObject.transform.position startTransform.position this.gameObject.transform.rotation startTransform.rotation Quaternion.Euler (90.0f, angleAroundY, 0.0f) Move from point A to point B while (this.gameObject.transform ! endTransform.transform) float step speed Time.fixedDeltaTime this.gameObject.transform.position Vector3.MoveTowards (this.gameObject.transform.position, endTransform.transform.position, step) yield return null yield return null I checked and the step variable is constant.


Attach component of other Object to a variable within Unity Inspector This question might sound a bit stupid and I'm sure there is a simple solution for this .. I'm just not finding it Actually all I want to do is attach the MeshRenderer Component of this Object to a variable of a script on another Object like Problem As soon as you click on the Capsule Object ofcourse the Inspector changes to this Object and I cannot drag in a component to the previous selected Object anymore. I know there are a lot alternatives like linkin only the GameObject e.g. as MeshObject and later in code refer to MeshObject.GetComponent lt MeshRenderer gt but I wondered if this can be done directly, too.


Lighting large scene with dynamic lights Unity3D I am working on a game project where most of the action takes place in a large scene that is built to look like a space station. Because it is all technological and enclosed, I can't use a directional light to light the whole scene, and I need to be able to change the color of the lights for an alarm system. I can't bake the lights, because then I can't change their color, and I can't leave them all as dynamic lights, because I have about fifty spot lights, and they take up a huge amount of memory, so much so that the lights can't even render on mobile devices. Is there any way to do this without baking? I am getting about 3000 batches in the Unity Editor Stats on average, in some places it is higher. Even viewing the game in full screen in the editor makes the game run super slow because of the amount of rendering it has to do, and I have a pretty new computer. Here's a picture of my scene (As you can see, it is fairly large as you are able to see the UI box clearly from the scene editor) And here's the Stats box Here is an example of my scene in play mode UPDATE I removed the shadow casting, which isn't necessary for my project, and it improved the framerate slightly, and the batches number is smaller, averaging out at about 1500 now, but the performance still is not optimal.


Basic Character Controller Not Working Properly in Unity I've been trying to setup a simple mouse camera which I had all the code working fine, except when I move with wasd and move my mouse to turn the camera simultaneously the input freezes up and gets stuck repeatedly inputting whatever the last input was. I've tested the simplest way to replicate the issue and it doesn't even need a camera for the issue to come up. If anyone would like to test and try to replicate the issue these are the steps its super fast and simple. create new project(basic PC 3D project) create a plane, and a cube Add a basic character controller script to the cube (this time I used the official Unity code to be sure it's not an issue with code) and that's it, that's actually all that was needed to create the issue for me. And to explain to anyone who may want to test it the issue is as follows when you use wasd keys normally, everything works fine and the controls are responsive. However if you hold down one of the wasd keys while also moving your mouse (just wiggling the mouse should suffice) suddenly things will lock up and the cube will keep moving for a bit even after you let go of the respective wasd keys. In general if you hold a direction while simultaneously wiggling the mouse for a longer period of time, it will extend the amount of time the cube keeps moving after you let go of the direction. And this was done on Unity version 2020.1.16f1 If anyone has any idea what the issue may be its really appreciated.


Are Differing Store Identifiers Necessary with the Unity IAP Plugin? I am looking at implementing the new Unity In App Purchasing API for the first time. Through the guide and the tutorial, I see that there is the ability to add different store identifiers for product ids that vary across stores... and all the examples reference that way of doing it. Eg. public class MyIAPManager public MyIAPManager () var builder ConfigurationBuilder.Instance(StandardPurchasingModule.Instance()) builder.AddProduct("100 gold coins", ProductType.Consumable, new IDs "100 gold coins google", GooglePlay.Name , "100 gold coins mac", MacAppStore.Name ) In my case, my product id's DONT differ, so this seems like unnecessary code bloat to implement it this way... but I don't see any other option? EDIT Argh, I'm using VS Code on OS X, which is getting better, but still has issues, such as having problematic code completion API referencing issues, so didn't see the overloaded method option... It's simply enough to do this var builder ConfigurationBuilder.Instance(StandardPurchasingModule.Instance()) builder.AddProduct("100 gold coins", ProductType.Consumable)


How to enter a level when touching an object I am working on a project in Unity 4.6.1f1 and I was wondering how can I make a cube touch another cube to go to the next level (the image below)? ! EDIT I made a script and put it on the purple cube then enabled "is trigger" on the purple cube, but the blue cube goes right through it. Inspector And the code EDIT 5 15 15 I edited my script and I was wondering if I'm doing something wrong.


FPS controller initializing at bizarre location I have got the hang of basic construction, terrain modification, applying materials, placing trees, etc. I have created a water plane, positioned my terrain above it, and am able to sink lakes and pools, and raise hills and mountains. Built a couple of primitive structures too. Initially (before mucking about with the Y position of the terrain) I was also able to invoke Gameplay mode and walk around my game using FPS Character Controller. I could walk into and out of my structures and hike over the hills and valleys of my terrain. However, since changing the Terrain Heightmap to make the "sinkhole" (negative altitudes) work, I am having the strangest trouble with my FPS Character Controller. I position it at a reasonable height above the terrain, and everything looks fine in Editor mode but when I start Play mode my FPS character starts out miles below the world, looking up at the underside of the terrain. So far nothing I have tried will make the FPS Controller start in the location where I have dragged it in Editor mode. I have tried Saving Scene and exiting and reloading. I have deleted and recreated the FPS controller. No matter what I do, it persists in initializing itself in this oddball "way below the world in outer space" location. I have googled diligently but have not found any mention of this problem. Presumably I'm skipping some important step, but tutorial videos don't offer any advice beyond "drag the fps controller into the scene and it should work."


Making player movement direction follow players facing direction if (controller.isGrounded) moveDirection new Vector3 (Input.GetAxis ("Horizontal"), 0, Input.GetAxis ("Vertical")) moveDirection transform.TransformDirection (moveDirection) moveDirection speed if (Input.GetButton ("Jump")) moveDirection.y jumpSpeed moveDirection.y gravity Time.deltaTime controller.Move (moveDirection Time.deltaTime) This works. I can manover my player in any direction. With the awsd keys i can create 8 directions. I would like player to rotate towards the direction of the keys pressed. This is a top down game. So W D would take you diagonally right up. S D would take you diagonally right down. I want the player to rotate into that direction, but also move the direction it is facing. Like a car. So if it is facing a complete different direction then it would actually move not in the target direction for a while until it has the target direction. Am i making sense? if (moveDirection ! Vector3.zero) transform.rotation Quaternion.LookRotation (moveDirection)


Unity Ads showing test ads I am implementing Unity Ads in my game and for some reason I have the test ads showing up in my production version of my app. I have the advertisements initialized with test ads turned off and I have even gone into my settings on the Unity Ads admin and set it to force test ads to be off. I'm not sure what else to do here. Here is how I am initializing Advertisement.Initialize("myID", false)


Get closest Child to cursor I'm currently rewoking my RTS cover system. This should highlight the closest coverspots from my mouse cursor and sent the units to these locations. everything works, but I can't get the closest sport, it always selects the sames ones, regardless to the mouse position. These cover spots are child objects of the obstacle, that has this script attached. This is my not working implementation of the idea void Update() var dist Mathf.Abs(transform.position.z Camera.main.transform.position.z) var v3Pos new Vector3(Input.mousePosition.x, Input.mousePosition.y, dist) v3Pos Camera.main.ScreenToWorldPoint(v3Pos) mousePos v3Pos ... public void getPointDistances() foreach (CoverPosition pos in coverPositions) if (!pos.occupied) pos.distanceToCursor Vector3.Distance(pos.transform.position, mousePos) Array.Sort(coverPositions, delegate (CoverPosition x, CoverPosition y) return y.distanceToCursor.CompareTo(x.distanceToCursor) ) Later, I simply Iterate over the sorted array and make it visisible. I'm woking on this for hours, but i cannot find, a solution why it always displays the same cover spots. I hope, someone can find my (possibly stupid) error. Edit I also tried this, but tata returned always the same values, regardless of my mouse positioning Ray ray Camera.main.ScreenPointToRay(Input.mousePosition) RaycastHit hit if (Physics.Raycast(ray, out hit)) mousePos hit.transform.position


How do I create a sphere by script? I want to add a sphere at runtime via script. I have the following code which compiles fine. At runtime however, no sphere is added to the scene. I have attached the debugger to the script, and I have set breakpoints at each line. After the line Material nMat new Material(Shader.Find("Lit")) I'm using the URP the debugger "blanks" out, it doesn't hit the next line. What am I doing wrong? Thank you! using System.Collections using System.Collections.Generic using UnityEngine public class SphereMaker MonoBehaviour private GameObject Sphere void Start() Sphere GameObject.CreatePrimitive(PrimitiveType.Sphere) Sphere.AddComponent lt MeshFilter gt () MeshRenderer nRenderer Sphere.AddComponent lt MeshRenderer gt () Material nMat new Material(Shader.Find("Lit")) I'm using the URP if (nMat null) Debug.LogError("no mat!! n") nMat.color Color.red nRenderer.material nMat Sphere.transform.localScale new Vector3(0.4f, 0.4f, 0.4f) Sphere.transform.position new Vector3(0, 0, 0)


How to make Procedual Context Sensitive Mesh Generation during Runtime In the game that i am trying to make i essentially generate an infinitely generating maze that has no dead ends and each corridor is of the same width. i have successfully managed to create this system however once i have created the floor tiles on which you are supposed to walk on i need to generate some walls. these walls surround the floor tiles preventing you from leaving the floor tiles. the system that i have for making these walls right now is very inefficient and redundant so, i would like to find a better way of doing so. my current system for making these walls first, a Floor Builder lays out all the required floor tiles then i have a wall builder game object with numerous empty games objects in a single row that each have a script attached to them that checks if there is a collision on their current tile. if there is a floor tile nothing happens else a wall game object is spawned which is essentially a 1x1x1 cube that has a collider attached to it. once all the checks have been done the parent game object is move 1 tile upwards and the process repeats itself. once the player is out of range of the walls that are left behind a garbage cleaner game object just destroyed them. this system can be improved in terms of code by using arrays instead of multiple game objects however that would still not improve the performance since the cause of the performance drop on slower devices it that a lot of game objects have to be spawned and tracked. the whole system is very inefficient and produces about 100 to 500 game objects which are destroyed later on. i have attached a picture to give an idea of how the system works ignore the cubes and other entities. there are also other solutions i have looked into and made Single line Builder basically, at the boundary, i put a single game object that starts and stops when a player is nearby or not it goes from right to left checking each 1 unit of space for a floor tile and spawning a wall if there isn't. this was a much more efficient but slow solution which i later improved on. Smart Single line Builder its mostly the same as the previous one however once it is in an empty spot it fires a raycast on its left side and when that ray hits a floor tile it uses the information obtained with its current coordinates to make a single row big wall instead of multiple walls this system worked much better but was still so slow that the player is able to run faster than the system can make walls. The kind of system that i would like to have a simple quad that sits below the floor tiles and moves along with the player. the quad is essentially pulled upwards in places where there isnt a floor tile. i have no idea how to make something like this.


Splitting a prefab into two These hands are in a single prefab. I want to split this into two so that I can make bones for each of them separately and use them with leap motion. How can make each of these hands as a single prefab? Also, I'm using Unity 2018.


Why is my alpha transparency not working correctly in Unity? In Unity I have never seen a bug quite as weird as this one. As usual, I import my texture with a transparent background and then check the alpha is transparency box and apply it, and everything seemed okay. It had worked like it usually does and made the background of my texture transparent. When I apply it to an object or even just paint it onto the terrain it shows the original texture, but in the areas where there should be nothing it replaces it with some nightmarish plaid hell. I have tried other transparent textures but that doesn't seem to work either same result but for each different picture there is a different pattern and color of plaid. I really would appreciate any help I can get on this because I'm just stumped.


Long occluding geometries in Resonance Audio for Unity I'm currently looking into using resonance audio (https resonance audio.github.io resonance audio ) for accurately modelling the audio for an environment that approximates to a long corridor with a series of bends. I want to have a sound at the end of this corridor that the user can hear at any point in the corridor based on the sound reflections along the corridor. I have tried a few of the options presented by Resonance Audio Placing reverb probes along the corridor. This seems like the ideal option, however a reverb probe will only apply its baked in reverb profile to sound sources inside the probe. If I try to make the probes larger then they seem to take into account all of the geometry of the corridor at once and things get exceedingly echo ey and consistent regardless of where I am in the corridor. Turning the corridor model into an audio room. This isn't apropriate as it has many of the same issues as a large reverb probe, and also doesn't actually model the space itself. Has anyone had any experience with hearing distant sounds in Resonance Audio environments like this? At this point I have a feeling that Resonance Audio is just not built for this particular situation.


OnTriggerEnter is it called in both collider object? I've 2 object a Player and a Bonus object. In both script I've "OnTriggerEnter" script. In Player OnTrigger I Take Bonus value and add it to my Player (health, point, ammo) In Bonus OnTrigger I Play audio (when take it), Play Particle System and so on... But, it seems it's called only Player's OnTriggerEnter ... Why ? In Unity, if I have OnCollision OnTrigger enter in both object, which event is called ? Both ? Thanks


How to make procedurally generated terrain look realistic I generated a terrain using a technique from this blog post, everything worked well and I got the wanted result. This is what my generated island looks like As you can see the terrain have a polygon structure. Here is the graph that generated this mesh This is the code used to generate this mesh from the graph void DrawPolygons() List lt Vector3 gt vertices new List lt Vector3 gt () List lt int gt triangles new List lt int gt () List lt Color32 gt colors new List lt Color32 gt () foreach(Center c in centers) float zp zScale c.elevation vertices.Add(new Vector3(((Vector2)c.point).x,zp,((Vector2)c.point).y)) Color c0 getColor(c) colors.Add(c0) int centerIndex vertices.Count 1 var edges c.borders int lastIndex 0 int firstIndex 0 for(int i 0 i lt c.borders.Count i ) if(edges i .v0 null amp amp edges i .v1 null) break get voronoi edge Corner corner0 edges i .v0 Corner corner1 edges i .v1 get vertices height float z0 zScale corner0.elevation float z1 zScale corner1.elevation add color if(edges i .river gt 0) c0 Color.cyan else c0 getColor(c) colors.Add(c0) colors.Add(c0) creat voronoi edge points Vector3 v0 new Vector3(((Vector2)corner0.point).x,z0,((Vector2)corner0.point).y) Vector3 v1 new Vector3(((Vector2)corner1.point).x,z1,((Vector2)corner1.point).y) add points to vertices vertices.Add(v0) var i2 vertices.Count 1 vertices.Add(v1) var i3 vertices.Count 1 add triangles calculating surface normals so i can always add triangles clockwise correctly var surfaceNormal Vector3.Cross (v0 (new Vector3(((Vector2)c.point).x,zp,((Vector2)c.point).y)), v1 (new Vector3(((Vector2)c.point).x,zp,((Vector2)c.point).y))) if(surfaceNormal.y gt 0) AddTriangle(triangles, centerIndex, i2, i3) else AddTriangle(triangles, centerIndex, i3, i2) firstIndex i2 lastIndex i3 calculating uv's Vector2 uvs new Vector2 vertices.Count for (int i 0 i lt uvs.Length i ) uvs i new Vector2(vertices i .x SIZE, vertices i .z SIZE) mesh.Clear() mesh.vertices vertices.ToArray() mesh.triangles triangles.ToArray() mesh.uv uvs mesh.colors32 colors.ToArray() mesh.RecalculateNormals() mesh.RecalculateBounds() meshFilter.sharedMesh mesh meshCollider.sharedMesh mesh I would like to know if it's possible to have a noisy realistic looking terrain from this. How would I implement such a thing? Basically I want something with no hard edges, terrain that looks smooth but not too smooth, something like this video shows


Why aren't my Unity Ads showing "real" ads? I don't have quot Enable Test Mode quot checked under in the ads setting in Services, but when ads pop up on my published game, it's showing Unity ads as if the test mode is on. How can I fix this? Thanks! This is the code I use to add the ads Advertisement.Initialize(GooglePlay ID, GameMode) Advertisement.Show()


Creating dependent values in the Unity inspector I want to create a few values which will be dependent on each other. Specifically, I want total sum of few values always be 100 In unity inspector no matter how I tweak them. E.G. int total 100 int one 20 int two 30 int three 45 int four 5 How can I make other values adjust automatically if I tweak one of them in Unity Inspector?


How do I save variables and load them in Unity with JavaScript? I made a game and i want to save the high score and load it back. I need to save 3 variables and load them when the game starts. How do i do it?


Unity built app crashes when using particle system I have scenes with some basic flame effect. Its max particle count is 20 and there are not more than 4 5 instances active on the screen at once. I even checked the profiler but the memory usage was around 150 MB maximum. Given these, all runs fine in the editor but once the particles become visible, the game crashes every time. I tested this on a virtual Nexus tablet. I'm using Unity 2017.1.0p4. If anyone has encountered an issue like this, I'd appreciate any help to get around this. EDIT the built game crashes on PC as well (made a final build for PC, using the same PC). EDIT2 So I was able to trace the issue back to the few following lines var mf transform.parent.gameObject.GetComponentFromParentRecursive lt MeshFilter gt () if (mf ! null amp amp mf.mesh ! null) var sh2 system.shape sh2.mesh mf.mesh return public static class GetComponentRecursive lt summary gt Returns the first Component (T) found on the parent or its children the gameobjects on the same level as this is called on. lt summary gt lt typeparam name "T" gt lt typeparam gt lt param name "g" gt lt param gt lt returns gt lt returns gt public static T GetComponentFromParentRecursive lt T gt (this GameObject g) where T Component if(g.transform.parent.GetComponent lt T gt () ! null) return g.transform.parent.GetComponent lt T gt () else foreach (Transform c in g.transform.parent.transform) if(c.GetComponent lt T gt () ! null) return c.GetComponent lt T gt () return null Please bear in mind that GetComponentFromParentRecursive works, can use it for sprites, no harm done. When I comment out the first few lines, it doesn't crash(just lost functionality). Any ideas why this might cause a crash? And only in built game?