Switching between meshes vs Loading only specific mesh I am currently developing an online multiplayer game on Unity. In the game, the character of each player will be assigned its mesh after the game receives parameters (their meshes' names) for each character from the server. Assigning each character's mesh can happen after the main scene is loaded. I am wondering whether I should make each character's object the same by having every mesh possible loaded into it and only activate the corresponding mesh for that player. I should create a class that holds every mesh possible (like, mesh manager) and tell each character to use its mesh from that class. I should delay the characters' meshes loading to wait for the parameter from the server first. Then, load the mesh after the scene has been loaded. I am not sure if specific assets can be loaded outside of its scene in Unity. If anyone has any different solutions, feel free to suggest. Thanks in advance.


Enemy shake vibrate when following character I am using the arongranberg A path finding project to create way points for one enemy to follow the player. However, the enemy vibrates back and forward by about 0.1 0.2 unit distance when moving. I have done a lot of research regarding this problem in the past few days but to no avail I could not find a solution that solves it. This is link to a gif to show what I mean. I have tried, changing Application.targetFrameRate 30 changing fixed update to update and vice versa using rigidbody2d and turn interpolate on plus using velocity to move turning iskinematic on and off using translate to move. none of the above solution works. Below is the script I have for my enemy. Any advice would be appreciated. using UnityEngine using System.Collections Note this line, if it is left out, the script won't know that the class 'Path' exists and it will throw compiler errors This line should always be present at the top of scripts which use pathfinding using Pathfinding public class AstarAI MonoBehaviour The point to move to public Transform target private Seeker seeker The calculated path public Path path The AI's speed per second public float speed 200 The max distance from the AI to a waypoint for it to continue to the next waypoint public float nextWaypointDistance 0.02f The waypoint we are currently moving towards private int currentWaypoint 0 Rigidbody2D rb public void Start () rb this.GetComponent lt Rigidbody2D gt () seeker GetComponent lt Seeker gt () Start a new path to the targetPosition, return the result to the OnPathComplete function seeker.StartPath( transform.position, target.position, OnPathComplete ) public void GoToNewTarget(Transform newTarget) path null currentWaypoint 0 nextWaypointDistance 0.02f target newTarget seeker GetComponent lt Seeker gt () seeker.StartPath( transform.position, target.position, OnPathComplete ) public void OnPathComplete ( Path p ) Debug.Log( "Yay, we got a path back. Did it have an error? " p.error ) if (!p.error) path p Reset the waypoint counter currentWaypoint 0 public void Update () if (path null) We have no path to move after yet return if (currentWaypoint gt path.vectorPath.Count) Debug.Log( "End Of Path Reached" ) return this.GetComponent lt Rigidbody2D gt ().MovePosition (path.vectorPath currentWaypoint ) Debug.Log (path.vectorPath currentWaypoint ) Direction to the next waypoint Vector3 dir ( path.vectorPath currentWaypoint transform.position ).normalized GetComponent lt Rigidbody2D gt ().velocity new Vector2 (dir.x 3, dir.y 3) Vector3.MoveTowards(transform.position, path.vectorPath currentWaypoint , 2 Time.fixedDeltaTime) dir speed Time.deltaTime rb.velocity dir this.gameObject.transform.Translate( dir ) Check if we are close enough to the next waypoint If we are, proceed to follow the next waypoint if (Vector3.Distance (transform.position, path.vectorPath currentWaypoint ) lt nextWaypointDistance) currentWaypoint return


Health zone heals player but I have a problem Hello I am creating a special health zone that gives the player health and my current scripts health is going up super fast and I want it to go up by 2 hp per second. How would I do this? Here is the health zone script. public PlayerHealth playerHealth public float healthGain 2f void OnTriggerStay2D(Collider2D other) if (playerHealth.currentHealth lt playerHealth.maxHealth) playerHealth.currentHealth (int)healthGain playerHealth.healthBar.SetHealth(playerHealth.currentHealth) if (playerHealth.currentHealth gt playerHealth.maxHealth) playerHealth.currentHealth playerHealth.maxHealth playerHealth.healthBar.SetHealth(playerHealth.currentHealth)


Unity3d High level literature Is there any high level literature for mid professional programmers for Unity? There are a lot of tutorials for beginners, but I can't find anything about main API, pipeline or engine architecture. Recommend, please!


How to Detect Mesh Segmentation? I have a mesh like this (it's all a single mesh) How I can figure out that the one floating piece is completely disconnected from the rest of the mesh?


Is there a way to reference Unity UI object inside native code? Let's say we have a scene in Unity with canvas and InputField on it. Is there a way i can reference my InputField inside native plugin? Maybe i can pass it from Unity?


Detecting internet Connection on Unity connection to serve ads How can you detect someone's Internet connection in Unity? I see a lot of forums where people make a request to any site (mostly google.com) to check it, but it does not seem to be an elegant solution. With 3G 4G connections to serve Unity ads or admob interstitial, it takes a lot of time and crashes the game. Regards!


Rotating A 2D Cannon Based On Mouse Position I'm creating a game like bubble shooter, I have a cannon which is in the image bellow I want to rotate the cannon based on mouse position. So far I tried various solutions I found over the web but non of them are working, I know that I only need to rotate the cannon on the Z axis because this is a 2D game, so I don't touch X and Y axis. Does anybody know how can I rotate the cannon based on mouse position? Or at least provide me a sample script on where to start. Thank You.


what is use of ScriptableSingleton in Unity? in unity 2020.x Unity just has introduced scriptable Singleton. a class that derives from Generic Class Called ScriptableSingleton its like singleton but you only can have single instance of it and seems to be good for ScriptableObjects that need to be Forced to be Single. but there are some differences. they can be project Specific or Shared. they can get any format and unlike usual scriptableObjects they have no visualization in the inspector. the question is how should i use them and they are appropriate for which approaches? this is the link to the reference https docs.unity3d.com 2020.1 Documentation ScriptReference ScriptableSingleton 1.html


EnemyAI rotating on Y axis in opposite direction After a battle flag has gone off and the player has entered an enemy's battle zone I want to keep track of the player when it moves and make sure the enemy's Z axis is always pointing towards the player. Upon the player entering the battle zone, the enemy automatically marks the player as its target However there is a chance that the Z axis may not be pointing towards the enemy's target when the battle is first initiated. I decided to shoot a ray cast from the Z axis of the enemy when the battle flag goes off and rotate the enemy until the ray and the player intersect thus telling me that enemy's Z Axis is lined up correctly. the enemy always has a reference to its current target. My idea was that as once the enemy spots its target initially, it can save the position of the most recent spotting and then take the delta of the CurrentTargetPosition.x and the LastSpottingPosition.x If the delta is positive rotate right and if the delta is negative rotate left. THE ISSUE my math or logic must be flawed somewhere because although it works sometimes, other times the enemy will randomly rotate itself in the opposite direction and the ray cast will essentially take the long route to hit the player instead of the shortest route as intended. Also the Local Origin of the enemy and the player are at different height respectively but I dont think that should matter in my case Code Below. create ray from enemy position orgin and point it on the Z Axis Ray ray new Ray(CurrentEnemyTransform.position, CurrentEnemyTransform.forward) RaycastHit hit if (Physics.Raycast(ray, out hit, 50f)) Debug.DrawLine(ray.origin, hit.point) ray hits current enemy target if (hit.transform CurrentTargetTransform) check if enemy has seen its target before while in this battle or is it the first time if (enemy.hasTargetLastPosition) replace old last seen position with most recent spotting enemy.ReplaceTargetLastPosition(hit.transform.position) or add the first spotting of target while in this battle else enemy.AddTargetLastPosition(hit.transform.position) ray is not intersectiing with the enemy's current target so rotate to look for it if (hit.transform ! CurrentTargetTransform) check if enemy has seen its target once before in battle if (enemy.hasTargetLastPosition) since last spotting has my target moved more to the left or right? if (enemy.targetLastPosition.value.x gt CurrentTargetTransform.position.x) rotate right CurrentEnemyTransform.Rotate( Vector3.up, 5f, Space.Self) rotate left else CurrentEnemyTransform.Rotate(Vector3.up, 5f, Space.Self) never seen target yet during this battle so default rotation to right till you found it else CurrentEnemyTransform.Rotate( Vector3.up, 5f, Space.Self)


Best way make static GameObject clickable 2D I've built a turn based battle combat game (like pokemon) but i'm stuck between a rock and a hard place. Asfar as i understod UI elements should be inside Canvas, while Players, Enemies, Items and etc... Should not be inside a canvas. Correct me if i'm wrong. I've tried different ways how to handle this situation. Such as make Enemy as a button, but seems not to fire. Since i think it has to be inside a canvas. Also make enemy which have animations as button, may not be a good idea? Update event, to check if the mouse is down and mouse position is converted with screentoworldpoint and see if the positions matches with the enemy position. Update event, to check if the mouse is down and rayCast see if we colide with something. But i dont feel like this is neccesary since the enemy does not move. So the position is always the same. Also if it's possible to take into consideration that every enemy is different size. But this is a minor detail, i would like firstly tackle the best way handle onClick event without the extra overhead. I would appericate any feedback on my dilemma.


How to add prefabs to the terrain and still retain scripts, colliders, etc.? I have been working on an old DOS styled game, and I began work on the trees for my terrain. Here is a group of them They, right now, are simply objects in the scene. This works, but is very cumbersome when mass placing them. I want to have them part of the terrain. I tried simply adding them as a detail mesh, but they didn't retain scripts nor colliders. Is there a way to accomplish this?


How do I find the name of the current audio clip being played? I have a title scene and a credits scene that use the same music. When I start my game the title scene music plays, and I have my game set up so the audio manager is not destroyed on load. When I enter my credits scene I do not instruct any new music to play, but each time I reload my title scene the title music restarts because a script in the scene tells it do so. How can I get the name of the current audio track so that I will only play audio if it differs from what's currently being played? This is my "LevelMaster" script which is responsible for handling the audio in each scene. public class LevelMaster MonoBehaviour private AudioManager AudioManager SerializeField private string trackName private void Start() AudioManager GameObject.Find("AudioManager").GetComponent lt AudioManager gt () AudioManager.Play(trackName) public void PlaySound(string soundName) AudioManager.Play(soundName) public void StopSound(string soundName) AudioManager.Stop(soundName)


Record video and sound from device camera and show it as a texture I need to record and show video from a real camera device in iOS Unity and show that video as a texture in RawImage (Image of what I want) What I have tried so far Unity WebCamTexture API It shows the camera in a texture but it has two problems! It does not record audio and does not have an API to save video! Camera Capture Plugin I bought this plugin but unfortunately it does not have the feature to show video in a texture it just opens the camera device's application. EverPlay plugin I tried this plugin and it seems that it just creates a video from the screen and not the camera Unity Video Capture API There is also this API for recording video with sound but unfortunately it is part of Windows Mixed Reality and does not support iOS Using Objective C I tried to write the video recording section directly in Objective C, I did it but I could not find a way to embed that in the Unity scene I'm not sure it's even possible! ( what I tried) I appreciate any other solutions that can help.


Unity using WWW to download image from web. Not working from my own website, but does from other urls I have this script attached to a RawImage file in my games UI public class DownloadImage MonoBehaviour string url "http megabrogames.rf.gd pic.jpg" string url "https i.imgur.com xBSyvRx.jpg" IEnumerator Start () WWW www new WWW(url) yield return www GetComponent lt RawImage gt ().texture www.texture Both jpg files are the same. One I uploaded to Imgur, this works. The other is on my own website. The url to my website works fine, I have checked in on two computers and several browsers. All I get is the red question mark. But if I uncomment the other one instead it all works perfectly. My problem is that I have hard coded the url into the game, and I want to change the image each week. It has to be the same URL for that to work, but i think with Imgur it will auto assign whatever url it feels like. thanks for any help


Issue implementing wall jump in Unity I'm having troubles implementing a satisfying wall jump in Unity. I managed to detect collision with a wall, but when I press the jump button, the result is alway weird or very weak. I think this have to do with the 2D physic in Unity, but I have no idead how to handle it correctly. Here's my code with the concerned parts public void Move(float move, bool crouch, bool jump) If the input is moving the player right and the player is facing left... if (move gt 0 amp amp !facingRight) ... flip the player. Flip() Otherwise if the input is moving the player left and the player is facing right... else if (move lt 0 amp amp facingRight) ... flip the player. Flip() if (jump) if (!grounded amp amp walled) StartCoroutine(WallJumpRoutine()) void Flip() Switch the way the player is labelled as facing. facingRight !facingRight Multiply the player's x local scale by 1. Vector3 theScale transform.localScale theScale.x 1 transform.localScale theScale IEnumerator WallJumpRoutine() Vector2 wallJumpVector new Vector2(jumpForce 10, 20f) GetComponent lt Rigidbody2D gt ().AddForce(wallJumpVector, ForceMode2D.Impulse) yield return null To be more precise, the result I'm getting is either my player being moved a tiny bit (despite using the same force as my regular jump, which is working fine) or my player being moved a good distance but at very high speed (this is when I'm using ForceMode2D.Impulse). Any help?


Character axis gets messed up when I add the armature into it So basically Ive been working on a walking animation in Blender, but theres a problem when I import it to Unity, the axis get inverted The only thing that is messing it up is the armature that animates the character, if I only import the character itself the axis are normal, if I also import the armature, the axis get inverted...


Errors when baking lights in unity3d So, i'm developing a game in unity and avoided baking lightmaps untill now ( i just assembled my new workstation setup wich is capable of baking the lightmaps and not the computer ). And now i have opened my project, imported it nicely and all, went to the lightning tab and clicked generate lightning ( naturallly i had auto bake disabled). And everytime i do that i get a billion errors, and they do not stop popping up even after i force stop amp cancel, i have to clear baking data in order to do anything ( of course unity is laggy as hell when it's spitting out these errors ). I even tried just a simple scene with just a plane on it. It's the same. I checked and it works fine on another empty project, wich lead me to the conclusion that some texture in my assets folder is causing the error even though it's not on the scene at all. In this case i'm kina doomed, i have absolutely 0 idea wich texture could this be ( i have quite a lot of them) and why would it even cause problems. Any way to check that? Or maybe does somebody know another possible reason for this problem? I tried to do research but found literally nothing. No thread about the issue, nothing. Not even the same errors. Thanks in advance. PS i have baked amp realtime GI disabled


Cardboard on iPhone 5 doesn't render on stereo Has anyone ran into this? I'm on Unity 5.1.1p3, Cardboard Unity Integration v0.5 (5 28 2015) and an iPhone 5 running iOS 8.3 (12F70). I made a game that uses Cardboard and on an iPhone 6 the screen renders as expected two offset cameras. On an iPhone 5 however, while the screen does show the 2 viewport masking and the distortion correction, it's actually a single camera that is being rendered, defeating the purpose of Cardboard. Here's what I mean. This is the iPhone 6, as expected And this is the iPhone 5, which is wrong Any ideas? Some extra info The iPhone5 can only use GLES2. It doesn't support ES3 or Metal. But what I did notice is that if I make a build for GLES2 the first time the app runs on the device (be it iPhone 6 or 5), when the Cardboard camera gets enabled, the app crashes If then I quit the app and start it again from the phone without it being hooked up to Xcode, on the iPhone5 I get the wrong rendering I've shown while in the iPhone 6 the app just crashes again. And if instead I make my build with automatic graphics API detection, what happens is that on iPhone6 it goes to Metal mode and so it works fine and on the iPhone5 it goes to GLES2 mode which, as stated before, crashes if attached to Xcode but otherwise just runs only that with the wrong rendering.


Autonomous robot moving from 1 object to the next object This question falls in line with my last question Unity 3D create autonomous moving robot in house first person camera movement What I have I have a 3D model of a house a first person camera with movement through the house a robot that autonomously moves. What I want I want the autonomously moving robot to search the house for certain objects. I have placed 4 guns (same model) in the house. This is the code I have now. This works for 1 gun not multiple game objects using UnityEngine using System.Collections public class MoveTo MonoBehaviour public Transform goal void Start () NavMeshAgent agent GetComponent lt NavMeshAgent gt () agent.destination goal.position What I want extra If possible, I want it to communicate with the person navigating the "game" with the first person camera. For example, if it finds a gun, I want it to say to the person "playing" the game I found a gun. If it finds the next one I found 2 guns I found 3 guns etc etc. For that, I used the following code for the player using UnityEngine using System.Collections public class UGV MonoBehaviour public Player player assign this variable in the inspector, or using another method public void CallMethodBInPlayer() if(player ! null) player.MethodB() public void MethodA() do something (Robot) And the same for the robot (but changed accordingly). I will be honest with you that I have very little understanding of programming or Unity. I want you to know I've been looking for an answer for many hours but even though the idea might be too complicated for me just yet, I still hope you can (and want) to help me )


NavMesh.SamplePosition() fails after rebaking NavMesh? So today I was refurbishing a scene when this happened. After baking a new Navmesh the SamplePosition() returned only infinity. I tried a lot of things out but eventually went back to an older version of my project. Sooner or later I will have to bake a new Navmesh though, so I'd really like to know what happened there. Here is the part of the code that appears to cause trouble Vector3 randomDirection Random.insideUnitSphere roamRadius NavMeshHit hit NavMesh.SamplePosition(randomDirection, out hit, roamRadius, 1) direction hit.position And of course this, since it tries to look into infinity I suppose transform.LookAt(transform.position direction, Vector3.up) Again, this code works fine. Only after baking a Navmesh this fails horribly.


In Unity, how can I register a custom file type that is always opened with my game? I want my players to be able to create their own scenes as custom levels, save them as files (say custom1.gamelevel), and open them directly in my game program by double clicking the level file, rather than having to go through the steps of opening the game, browsing to the file in my menus, and then loading that scene level. I already have loading custom levels covered. I just need a way to associate this custom file type with my game which can open it. I am mainly interested in a Windows based solution. How can I do this?


Can't figure out what's making the player teleport back to spawn I've been working on a multiplayer game that uses pathfinding and I'm really confused over this one weird bug. On your screen, the other player glitches between the spawn point and his current location. It seems like there's a problem with the interpolation as it doesn't do this when I comment out transform.position Vector3.Lerp(transform.position, bestGuessPosition, Time.deltaTime latencySmoothingFactor) Does this have anything to do with the way I'm moving the player? using UnityEngine using UnityEngine.AI using UnityEngine.Networking public class MinionController NetworkBehaviour public Camera cam public NavMeshAgent agent Vector3 velocity Vector3 bestGuessPosition float ourLatency float latencySmoothingFactor 10 Update is called once per frame void Update() if (hasAuthority false) bestGuessPosition bestGuessPosition (velocity Time.deltaTime) transform.position Vector3.Lerp(transform.position, bestGuessPosition, Time.deltaTime latencySmoothingFactor) return if (Input.GetMouseButtonDown(0)) Ray ray cam.ScreenPointToRay(Input.mousePosition) RaycastHit hit if (Physics.Raycast(ray, out hit)) agent.SetDestination(hit.point) Command void CmdUpdateVelocity(Vector3 v, Vector3 p) transform.position p velocity v RpcUpdateVelocity(velocity, transform.position) ClientRpc void RpcUpdateVelocity(Vector3 v, Vector3 p) if (hasAuthority) return velocity v bestGuessPosition p (velocity (ourLatency))


Instantiated Object returns Null outside Start method I'm attempting to access an instantiated 'goalTemp' GameObject from a different function inside the same script. I'm getting the information in the Start method, assigning the GameObject find get component script code to a variable. When I'm printing the results outside the Start method, it returns null, even though the 'goal' variable is public. void Start() GameObject goalTemp (GameObject)Instantiate(goal,respawnGoalLocation CreateLevel.currentLevel 1 ,Quaternion.identity) goal goalTemp.gameObject public void Explode() Debug.Log(goal) Instantiate(rockParticle, goal.transform.position, goal.transform.rotation) Instantiate(explosionParticle, goal.transform.position, goal.transform.rotation) What am I doing wrong here? Thanks for your time!


Prototype experience Unity3D vs UDK Has anyone yet prototyped a game in both Unity3D and UDK? If so, which features made prototyping the game easier or more difficult in each toolkit? Was one prototype demonstrably better than the other (given the same starting assets)? I'm looking for specific answers with regard to using the toolkit features, not a comparison of available features. E.g. Destructable terrain is easier in toolkit X for reasons Y and Z. I can code, so the limitations of the inbuilt scripting languages are not a problem.


Unity network player synchronization issues with HingeJoint(s) I have a vehicle with custom wheels which are connected to it by the HingeJoint components. Everything works perfectly when using this car in single player mode. Wheels are actually as Cylinders. They have HingeJoints attached through which they are bound to the vehicle's Rigidbody. Then I set JointMotor.force and the wheels are getting rotated and the vehicle is moving. It all works very naturally in terms of physics, I don't need to emulate anything. Still, there is an issue with network synchronization in multiplayer mode and I have no idea how to solve it. It's said that the proper way to sync the position of a physical object is to use rigidbody.MovePosition(), but any manipulation with Rigidbody leads to the collapse of the vehicle hinge joints. The only method that works is setting transform.position directly. But this is not recommended for physics and it doesn't allow to synchronize the vehicle smoothly with no twitching. Is there a way to solve this somehow? I'm using Photon for networking (if it matters in the question context).


How do I make my prefabs spawn behind the UI? I'm making a game where three characters spawn in specific locations. I made three gameobjects called stations so I could take the transform positions and spawn the three caracters there. And I have a UI element that is supposed to stay in front of everything. But the problem is that when I hit play, the three characters spawn in front of the UI element. I already checked the positions related to the camera but it doesn't seem to be it. Does anyone know how to help me?


Move car at same speed I want to move car on each game play run with same speed. At present I was getting each time different velocity. I want to fix that. Here is game play area on which I was moving car At present I was moving car in infinite motion without any kind of control. When it collide with wall, it will its direction based on collision calculation. Here is my source code that I was using to move car void Start () direction new Vector2 (Random.Range ( 1f, 1f), Random.Range ( 1f, 1f)) void FixedUpdate () float angle Mathf.Atan2 (direction.y, direction.x) Mathf.Rad2Deg float targetRot Mathf.LerpAngle (myRigidbody.rotation, (angle 90f), 0.1f) myRigidbody.MoveRotation (targetRot) myRigidbody.velocity direction speed myRigidbody.MovePosition (myRigidbody.position direction Time.deltaTime speed) Debug.Log("vel mag " myRigidbody.velocity.magnitude) void OnCollisionEnter2D (Collision2D other) ContactPoint2D contact contact other.contacts 0 direction 2 (Vector3.Dot(direction, Vector3.Normalize(contact.normal))) Vector3.Normalize(contact.normal) direction Following formula v' 2 (v . n) n v direction 1 Dont know why I had to multiply by 1 but it's inversed otherwisae Vector2 reflectedVelocity Vector2.Reflect(direction, contact.normal) direction reflectedVelocity At present on each run of car, I was getting different velocity that I have checked via debug statement. So my target is to move car with same speed always.


unity2D Top Dow Mobile rigibody2D im using this code for my 2D TopDown mobile player movement.but when i move player With UI Image buttons player keep moving.it didnt stop.and also player starting of move he is very slow. the he accelerate his speed.how can i fix this. i add BoxCollider 2D and Rigibody2D my sprite.the set Gravity to 0. this is my code. public class PlayerScript MonoBehaviour public float speed 150f float hInput void FixedUpdate() Move (hInput) public void Move(float horizontalInput) if (horizontalInput.Equals(1)) rigidbody2D.AddForce (Vector2.right) if (horizontalInput.Equals(2)) rigidbody2D.AddForce ( Vector2.right) if(horizontalInput.Equals(3)) rigidbody2D.AddForce (Vector2.up) if(horizontalInput.Equals(4)) rigidbody2D.AddForce ( Vector2.up) public void StartMoving(float horizontalInput) hInput horizontalInput


Replacing assets in Unity real time but keeping the references intact I'm looking forward to adding mod support into my game by allowing users to easily replace some assets with their own versions. The way I want it to work if there's, say, a certain texture in some folder in my compiled game, I replace the texture with the same name in my resources, but I keep references intact. That means that the texture will be replaced for every material using this texture. I don't want to change materials themselves to reference the new texture, mainly because I'll have to keep a list of materials for each texture, and because materials might be replaced by potential modder as well. It's also important to note that I want to give people the ability to change basically anything (but scripts). Sounds, music, textures, meshes, materials, fonts, localization files, shaders, so the list of references might be absolutely changed upside down and that is absolutely not the solution.


Unity Terrain Tools plants trees sideways My tree is clearly straight, but painting trees result in sideways ones. What can cause this? Tree is straight when placed manually as a prefab.


Get all supported resolutions for a monitor I've been receiving complaints from users that my game doesn't support the 16 10 aspect ratio. Currently I list everything in Screen.resolutions in a dropdown and allow the user to pick from that. I have since come to the understanding that the first element is not necessarily the native resolution of the monitor. I've found the Display class but this appears to only give the native resolution, not all scaled resolutions. E.g. if the monitor is 1920x1080 then I need a list of 1600x900, 1280x720, 640x360 etc. I thought about just multiplying by some scale factor but then I'm afraid I'll get something obscure like 885x497.8. And if I have a pre determined list of resolutions for a specific aspect ratio, how do I support obscure aspect ratios like widescreen for example.


How can I scale a color component by Time.deltaTime and still fit it into a byte? I am confused about this issue, and I can't find why I get this and how to fix it properly from the Google searches I've tried. This is a short version of my code byte redtarget 70 byte greentarget 222 byte bluetarget 255 byte opacitytarget 1 byte redcurrent 0 byte greencurrent 0 byte bluecurrent 0 void OnMouseOver() redcurrent redcurrent redtarget Time.deltaTime greencurrent greencurrent greentarget Time.deltaTime bluecurrent bluecurrent bluetarget Time.deltaTime if(redcurrent gt redtarget) redcurrent redtarget if(greencurrent gt greentarget) greencurrent greentarget if(bluecurrent gt bluetarget) bluecurrent bluetarget theobject.GetComponent lt Renderer gt ().material.SetColor(" EmissionColor",new Color32(redcurrent,greencurrent,bluecurrent,opacitytarget)) Please ignore the other errors that could have been introduced when I copy pasted it to here. And this is the error I get As you see the error, "cannot implicit convert type float to byte", the problem is caused by Time.deltaTime that returns a float value, and I need a byte due to Color32. Is there any way to turn Time.deltaTime to byte? Or should I use another type of color that use floating point numbers? I'm a beginner with Unity so I'm sorry if this has already been asked somewhere as I said, I can't find it on the Internet.


How to program an attack that I control with the arrow keys? I'm making a 2D game prototype in Unity and I want to have the player attack be a sword that hovers around the player with its direction being fixed to the direction you indicate with the arrow keys. So if the sword is in the upward position and you press the left button, you can see the arc it takes and an enemy in the way of that arc takes damage. The game is not a platformer. It's on a flat surface. edit I want to know how to have the sword hover in a radius to the player and point the direction i press the arrow keys. I want to get the action of moving the sword to these positions to do damage to an enemy. But if the sword is in a upwards position and the player presses down, I want it to do an action that attacks the whole radius around the player, on a cooldown. How would I go about programming this? I'm new to programming so I would greatly appreciate some helpful pointers. Edit2 So this is how far I have gotten public class SwordSwing MonoBehaviour public Transform swordHolder Update is called once per frame void Update () if (Input.GetKeyDown(KeyCode.LeftArrow)) swordHolder.transform.Rotate(0, 0, 90) if (Input.GetKeyDown(KeyCode.RightArrow)) swordHolder.transform.Rotate(0, 0, 90) if (Input.GetKeyDown(KeyCode.UpArrow)) swordHolder.transform.Rotate(0, 0, 90) if (Input.GetKeyDown(KeyCode.DownArrow)) swordHolder.transform.Rotate(0, 0, 90) I don't know if this is right, because when I use the arrow keys it just turns the sword 90 degrees and not to the specified position I want it to move to. So Candid Moon said that I have to use Mathf.Lerp() and StartCoroutine() but I have no idea how to use them. I'm not really sure how to animate this either, I have done some animations in Unity but have a hard time implementing them into anything. The hierarchy is now Player SwordHolder Sword Now I also have this script if (GetComponent lt Rigidbody2D gt ().velocity.x gt 0) transform.localScale new Vector3(1f, 1f, 1f) else if (GetComponent lt Rigidbody2D gt ().velocity.x lt 0) transform.localScale new Vector3( 1f,1f,1f) That flips the player sprite when i move left. This also flips the sword, I don't really want this. How do I stop it? Let me know if there is anything I missed, I'm trying to learn.


MySQL for MMO Development... What do i have to consider ? Im currently developing an little mmo. Its pretty basic, players can walk around... gather some resources... build some simple buildings and craft things. Before i began to develop i read a lot about benefits using MySQL... Now im not sure if MySQL was the right choice for such a project. Currently i store player specific data in real time, that means... once a player crafted, builded or gathered something, a server request is send which triggers a MySQL Query to insert a new Row into the specific table. This happens everytime a player moves, crafts, gathers or builds something. I dont only store player specific data in those tables... also world specific data, for example if one player visits a zone which was last updated 6 hours ago, i refresh this zone with resources and mobs. The server is generating them and after that, it inserts them as a bulk into the database. With only one active player this works fine... but i have no idea if this will still work with dozens or hundreds active players at the same time. The serverside itself is able to handle them... but i have no idea if the database is able to. I also heard bad stuff regarding table locks... That this is somekind of major iusse using MySQL, how does this effect dozends of database actions per seconds ? And could possible "share" be a solution for this ? What else do i need to consider while using MySQL for a mmo ?


Sprites lose quality when in Unity Whenever I drag a sprite sheet into unity, it, for whatever reason, distorts. Is there any way to remedy this? Original Distorted


Unity2D Wrapping a line around an object I have this 2d platformer made out of box colliders. I have the player connected to a point by a LineRenderer and a DistanceJoint2D, for use in physics puzzles. This tool lets him link to a location and then do grappling hook things with it, like retract the rope at speed to spiderman around. What I want to do is move the distance joint around the object, thus changing the angle at which the player is pulled. Like in this image. Very similar to this more general, unanswered question that doesn't not give any specific math. I know I'll be making a list of positions and then move the joint's anchor around whenever it wraps unwraps, but I'm not sure how to tell when and where it wraps on something.


How do I make a transition between two states to be slowly? Now it's doing the first New State then it's jumping to New State 0 Instead I want it to slowly move between the two states. I want to see the animation transition slowly changing from state to state. For example when you see a character sitting and then standing so to see the transition from sitting to standing slow.


Turn and point Animation not ending in correct position I have Right Turn, Point amp talk Mixamo animation. I am playing animation in this order Play Idle animation Turn animation Point Animation Then, run Turn animation again with speed to bring it back(reverse) and then finally played Idle animation and loop continue. But the problem is, each time when I return from step 4 my character rotation is different. And over different iterations the character rotation become completely changed. The rotation of the character increment in each iteration. How can I solve this problem? I am learning this but unable to understand.


Image looks GOOD on the editor but BAD (blurry) on the HTML5 export I have a red bar that looks good inside Unity editor, but when I export the build it looks very strange. Any idea on how to fix this? The image on the left is the one with the strange bad looking red bar...


Texture not working on object I have a project that I'm having a bit of trouble with. Let me try and explain. In short, I'm trying to apply a texture to an object, but instead it is a solid color. I built a building in "Autodesk 123d design", and exported it as stl. Then I used an online converter to convert it to obj, then added that to the unity scene. I created a material with a texture and tried to apply it to the object, but it was a solid color. I think the UVs on the object might be messed up. I tried some things in blender, but had no luck. Any ideas on how I can fix this? Edit Here is the 3D model I'm working with http www.123dapp.com 123D Design Conisbrough Castle Keep 4578568


Refresh UI after changing source code I was trying following things. GameManager bool gameHasEnded false public GameObject completeLevelUI public void CompleteLevel() completeLevelUI.SetActive(true) public void EndGame() if(gameHasEnded false) gameHasEnded true Invoke( quot Restart quot ,2f) void Restart() SceneManager.LoadScene(SceneManager.GetActiveScene().name) EndTrigger public GameManager gameManager void OnTriggerEnter() gameManager.CompleteLevel() I get a log in the console quot END quot . Earlier I was using Console.Log( quot END quot ) on CompleteLevel(), but I changed that source code. The old code seems to be working and not the new one. It's like Unity couldn't refresh that source code. (And I am sure that I have successfully saved the C file.) using System.Collections using System.Collections.Generic using UnityEngine public class PlayerCollision MonoBehaviour public PlayerMovement movement void OnCollisionEnter(Collision collisionInfo) Debug.Log(collisionInfo.collider.name) if (collisionInfo.collider.tag quot obstacle quot ) movement.enabled false FindObjectOfType lt GameManager gt ().EndGame()


Should I scale gravity for small objects? If I am working with objects that are small in real life, but in the Unity world they are scaled larger, should I increase the Gravity with the scale of the objects? For example, if an object of size one would actually be 10 cm across, would gravity scaled to be 10x make the object behave more like a small object would in real life. I know objects fall at the same rate, but the rate is the same so small objects fall more in proportion to their size don't they?


Changing alignment within a vertical layout group I have a vertical layout group that has text bubbles instantiated into it. Instantiating them always aligns them to "lower middle". However, I'd like to have them on opposite sides for a message app effect. Right now, I'm changing the anchoredPositions of each instantiated UI object in Update. Is there any better way of doing this?


Rotate an object on itself, from one random Quaternion to another I have a situation I have a 3D object in the world. let's say a sphere. I have 2 random directionnal vector vector A, and vectorB My question is How to I rotate over time my object, from A to B ? The vector A is important I don't want to simply rotate the forward of the object from current forward to B. I know I can use the function vector3 C Vector3.SmoothDamp(...) in unity to lerp between my 2 vectors A amp B. but then ok, I have vector3 C, how do I apply the rotationof my object to C ? if don't want to do gameObject.transform.forward C I want something like gameObject.transform.rotation SomeQuaternion(C, initial rotation A). or something. Thank you for help ! PS I don't want to parent unparent gameObject or something like that, i want the math answer, using Quaternion.


How can I have realistically bending flexing paper? I am a new hobbyist to Unity and I working on a game where the player goes around picking up clues in the form of paper notes to solve a mystery. So far, thanks to the help I got here, I was able to animate a note made from a UI canvas and an image in game world to fly and rotate to align itself in front of the first person camera. Although, it looks nice, it still looks like a rigid plank of wood rather than a piece of paper. Is there a way I could bend flew distort the canvas to give the illusion of a piece of paper rather than piece of wood? Is it possible to bend a canvas or should I go towards another solution, like using an actual plane or quad during the animation effect?


Are environments built in external applications or in Unity? Totally new to game development here I know models are never built in Unity, but what about environments? Is it common to say, build an office building environment with hallways and doors (sans furniture and props) in Blender and import that into Unity and assemble the scene there?


How can I avoid tight script coupling in Unity? Some time ago I started working with Unity and I still struggle with the issue of tightly coupled scripts. How can I structure my code to avoid this problem? For example I want to have health and death systems in separate scripts. I also want to have different interchangeable walking scripts that allow me to change the way the player character is moved (physics based, inertial controls like in Mario versus tight, twitchy controls like in Super Meat Boy). The Health script needs to hold a reference to the Death script, so that it can trigger the Die() method when the players health reaches 0. The Death script should hold some reference to the walking script used, to disable walking on death (I'm tired of zombies). I would normally create interfaces, like IWalking, IHealth and IDeath, so that I can change these elements at a whim without breaking the rest of my code. I would have them set up by a separate script on the player object, say PlayerScriptDependancyInjector. Maybe that script would have public IWalking, IHealth and IDeath attributes, so that the dependencies can be set by the level designer from the inspector by dragging and dropping appropriate scripts. That would allow me to simply add behaviors to game objects easily and not worry about hard coded dependencies. The problem in Unity The problem is that in Unity I can't expose interfaces in the inspector, and if I write my own inspectors, the references wont get serialized, and it's a lot of unnecessary work. That's why I'm left with writing tightly coupled code. My Death script exposes a reference to an InertiveWalking script. But if I decide I want the player character to control tightly, I cant just drag and drop the TightWalking script, I need to change the Death script. That sucks. I can deal with it, but my soul cries every time I do something like this. Whats the preferred alternative to interfaces in Unity? How do I fix this problem? I found this, but it tells me what I already know, and it does not tell me how to do that in Unity! This too discusses what should be done, not how, it does not address the issue of tight coupling between scripts. All in all I feel those are written for people who came to Unity with a game design background who just learn how to code, and there is very little resources on Unity for regular developers. Is there any standard way to structure your code in Unity, or do I have to figure out my own method?


Level Asset design for performance Unity I am a big fan of modular assets. Currently I am designing a 3d game for mobile and I don't know how I should create my levels to get the most out of the device. Should I... create lots of "small" (1x1x1 meter) assets and build my level using them or create one geometry for the entire level? What about textures? Should "all" objects share one highres texture and only display their part using the right UV settings (like say in minecraft)or should I create an individual texture for each object?


How to make a script work when clicked only on the given prefab? I am very new to unity but not to C . I am working in Unity 2D I made this prefab called LongLane. Its basically a collection of sprites of road, put together into a Gameobject. Now I wanted objects to spawn on the road when I ONLY click on the road, I can spawn the object on the road but they spawn regardless of where I click. I have written some code but they aren't clear and readable. So how do I make a script work only when clicked on that specific prefab


How to access GameObject to which MonoBehaviour is added from C Attribute Unity's RequireComponent inherits from System.Attribute. Somehow they made it that whenever component is added it has a reference to GameObject its being added to. So they can callAddComponent to it. I am trying to replicate that behaviour. My theory is that because UnityEngine.RequireComponent has types stored inside class they do it by reflection later. In method AddComponent lt T gt they get T class attributes from type and then try to cast them, get information from them, and apply to GameObject. If that is the case, then I doubt I will be able to do something with it, unless I have access to change AddComponent lt T gt somehow. Is there another way around it?(that is no problem to do in code (just extension), but what about how it will work in inspector) Maybe apply different method to Unity s default component addition. EDIT AttributeUsage(AttributeTargets.Class, AllowMultiple true) public class RequireComponentAttribute Attribute public RequireComponentAttribute(Type type, int quantity) if (quantity lt 0) throw new ArgumentOutOfRangeException("Required components quantity cannot be negative") if UNITY EDITOR endif


Control Torque Inputvector I'm faced with the following problem I'm trying to implement a rigidbody based movement for my submarine game which means I want (need?) to useAddForce() and AddTorque() in order to get proper collision detection. Currently I'm achieving the desired rotational behavior by quaternion multiplication rotation. But with this approach, the submarine bugs through the terrain. To avoid that it seems my only option is to use a rigidbody. Here's a video illustrating the problem. On the left is the correct behavior. I want to keep the nose pointing where it has been tilted at and not rotate around a fixed axis, Vector3.up in this case. How can I calculate the correct input for AddTorque(vec3) to get the result I need? Left attempt with quaternions (what I need) input2 Input.GetAxis("Sideways") transform.rotation Quaternion.Euler(0, input2 Time.deltaTime rotation speed, 0) transform.rotation Right attempt with torque (which doesn't quite work yet) in Update() rotateY Input.GetAxis("Sideways") void FixedUpdate() experimenting with AddTorque() and various inputs didn't get me any further rb.AddRelativeTorque(Vector3.up rotateY speed) I hope someone can point me in the right direction, thanks in advance.


Why moving platform script is not working? I have some code attached to a moving platform public Transform pos1, pos2 public float speed public Transform startPos Vector3 nextPos Start is called before the first frame update void Start() nextPos startPos.position Update is called once per frame void Update() if (transform.position pos1.position) nextPos pos2.position else if (transform.position pos2.position) nextPos pos1.position transform.position Vector3.MoveTowards(transform.position, nextPos, speed Time.deltaTime) private void OnDrawGizmos() Gizmos.DrawLine(pos1.position, pos2.position) But my platform does not go to the pos2 when it reaches the pos1. What is wrong here?


Unity Loading Image? I have a quastion about loading screen in unity. I don't want to make a scene between to levels Main Menu Loading Scene Game level . I want to use Canvas "Image"that run at the start of the game level and then disappear after few seconds Main Menu Game level . Is this good idea ?


Things not appearing in front of canvas (follow up) Follow up related question to Things disappear in front of Canvas I'm having a very similar problem, where things are not appearing in front of my canvas. This time a particle system. I have tried the suggestions outlined in my previous questions (which worked then) but this time none of them will work You can see that the particle system is on top of the children and also I have added a canvas and overwritten sorting (the two suggestions in my previous post) yet the particles are not visible in front of the canvas.


Unity 2D Platformer Controller responsiveness issue I've been designing some basic controls for a 2D platformer and managed to get the feeling that I've been looking for when moving and jumping, but something is not quite right, it's not very responsive. Most of the inputs are detected, but a lot of times, for example, the simple action of pressing some key to jump is completely ignored and the player ends up falling when the key was pressed at the right time. I don't consider that I'm developing on a laptop with low specs at all if that matters. Looking at some other questions it has always been said that input detection should be inside the Update function and that physics related stuff should be on FixedUpdate, however, it has not always been very clear what exactly should be on which function, as far as I understand it should go something like this...right? using System.Collections using System.Collections.Generic using UnityEngine public class PlayerController MonoBehaviour public float speed public float jumpForce public float groundCheckRadius public Transform groundCheck public LayerMask groundMask private float direction private bool facingRight private bool shouldJump private bool isGrounded private bool shouldFall private SpriteRenderer renderer private Rigidbody2D rigidbody void Awake() this.renderer GetComponent lt SpriteRenderer gt () this.rigidbody GetComponent lt Rigidbody2D gt () void Start () this.facingRight true this.shouldJump false this.isGrounded false this.shouldFall false void Update () this.direction Input.GetAxisRaw("Horizontal") this.isGrounded Physics2D.OverlapCircle(this.groundCheck.position, this.groundCheckRadius, this.groundMask) this.shouldJump Input.GetKeyDown(KeyCode.S) amp amp this.isGrounded if (this.facingRight amp amp this.direction lt 0 !this.facingRight amp amp this.direction gt 0) this.Flip() if (Input.GetKeyUp(KeyCode.S) amp amp this.rigidbody.velocity.y gt 0) this.shouldFall true void FixedUpdate() Vector2 velocity this.rigidbody.velocity if (this.shouldFall) velocity.y 0f this.shouldFall false if (this.shouldJump) velocity.y this.jumpForce velocity.x this.speed this.direction this.rigidbody.velocity velocity private void Flip() this.renderer.flipX this.facingRight this.facingRight !this.facingRight I'm not sure if I got the idea of Update vs FixedUpdate correctly because of this lack of responsive jumps, and I'm guessing that if I add some more mechanics, later on, those will react the same or worse. Something that I noted is that if I move everything to update it now feels right every time I press the jump button, but I'm still not sure if that should be the right approach when building tight controls. And I still feel lost about what everyone means by "You should manage physics in FixedUpdate", what do you mean by physics here?


why does Physics.Raycast always return my player game object instead of the object I clicked? I have 3D world. I want to detect when the player clicks on a game object in the world. In this image, I have 2 objects I want to detect mouse click on. The white sphere does have collider on it. The dumpster does not. The behavior is the same as noted below. I am getting the mouse down detection. When I check the RaycastHit, I always get the player game object transform and not the game object I clicked on in the world. If I remove the raycaster checks, then I get mousedown for anything in the game not just mouse down over the game object. I need to be able to distinguish between clicks on different game objects. I found a post here and added a PhysicsRayCaster, but it didn't change the behavior. The problem isn't getting the event. My problem is detecting which game object the player clicked on in the world. Here's my code public class InventoryItemSearchHandler MonoBehaviour private void Update() if (Input.GetMouseButtonDown(0)) Ray ray UnityEngine.Camera.main.ScreenPointToRay(Input.mousePosition) RaycastHit hit if (Physics.Raycast(ray, out hit)) CompareTo always fails because hit.transform.name is always "Player" and not the name of the object clicked on if (0 hit.transform.name.CompareTo(transform.name)) print("mouse down") EDIT In the image below (compared to the one above) I do get the correct transform in the RaycastHit type when I click on the white sphere (and when I click on the dumpster I get the player transform as noted above). So it looks like the player object is getting in the way. What would be causing that?


Updating transform position after root motion I have an animation of a character climbing with root motion in it (i.e. the character moves generally upwards for a couple of units during the animation). It is intended as a one shot, not a loop. The skeleton is fairly standard hips spine 1, hips right leg, hips left leg etc. The root is the hips and the pivot is between the soles of the feet. I know its generally best to make in place animations without root motion but scripting the upward movement using Vector3.Lerp etc looks unrealistic (in reality when rock climbing for example the upward motion will come in perdiodic bursts as the knees are first bent, then extended, rather than a constant movement upwards), so I want to keep the root motion in the animation. Problem is when the animation has finished Unity still considers the transform pivot to be in its original location, before the skeleton climbed up two units. Is there any way to instruct Unity that the new transform position is where the characters feet have ended up after the animation has finished? I figure I could parent the hips to an empty which moves the charaters around normally, detatch the empty before the root motion climb, move it by the same amount the hips moved then re attach but is there a less hacky way? Some kind of transform.returnToOriginalOffset method perhaps?


Issues loading in AudioSource at runtime using WWW class I am having an issue with loading in an OGG audio file to my project. Basically I want to set my game up so that players can drop audio files into a folder called Playlist in the game directory then they can listen to this music while they play. For some reason my audio clip never becomes instantiated. I have an Audio Source in my scene with this script attached to it. As you can see I have commented out some code for the time being as I am trying to get a simple case of only 1 audio file playing at this stage. So my question is what exactly am I doing wrong here? I have printed out the file path and it comes out as file B Users Matt Development Unity Projects Space Game Playlist 19 Tumbling Dice.ogg which is the location to my audio. However when I print out the audioLoader.audioClip.name it comes out as blank... RequireComponent(typeof(AudioSource)) public class MP3AudioImporter MonoBehaviour private List lt string gt playlist private string musicDir "B Users Matt Development Unity Projects Space Game Playlist " private int currIndex 0 void Start() string songs Directory.GetFiles( musicDir, " .ogg", SearchOption.TopDirectoryOnly) playlist new List lt string gt (songs) StartAudio() void StartAudio() WWW audioLoader new WWW("file " playlist currIndex ) Debug.Log(audioLoader.audioClip.name) audio.clip audioLoader.audioClip audio.Play() currIndex if (currIndex gt playlist.Count) currIndex 0 Invoke("StartAudio", audio.clip.length 0.5f)


World space coords for 2d images How can I make an 2d image using World space coords with a shape? Like a circle instead of a quad.In 3d you can modify the vertices but if I want a smooth circle there will be too much vertices. What I want to achieve is something like a cirle mask that will be move over the global texture at runtime. So has anyone done something similar? I've tried combining some shaders with two uv's one for world space and one for alpha uv mesh but it gives some weird artifacts. This is the how the shader looks on the right Shader "Unlit WorldspaceTiling" Properties MainTex ("Texture", 2D) "white" SubShader Tags "Queue" "Transparent" "IgnoreProjector" "True" "RenderType" "Transparent" LOD 100 ZWrite Off Blend SrcAlpha OneMinusSrcAlpha Cull Off Lighting Off ZWrite Off Fog Mode Off Pass CGPROGRAM pragma vertex vert pragma fragment frag include "UnityCG.cginc" struct appdata float4 vertex POSITION float2 uv TEXCOORD0 struct v2f float2 uv TEXCOORD0 float4 vertex SV POSITION sampler2D MainTex float4 MainTex ST v2f vert (appdata v) v2f o o.vertex mul(UNITY MATRIX MVP, v.vertex) Gets the xy position of the vertex in worldspace. float2 worldXY mul( Object2World, v.vertex).xy Use the worldspace coords instead of the mesh's UVs. o.uv TRANSFORM TEX(worldXY, MainTex) return o fixed4 frag (v2f i) SV Target fixed4 col tex2D( MainTex, i.uv) return col ENDCG


Is it possible to have a point light cast shadows but no reflection? I'm working in Unity 5.3.6. I have a point light that is simulating sunlight from a window. It looks great, except the floor reflects a bright white circle. I want the floor to reflect other lights in the room, just not this one. Is this possible?


Instantiating prefabs by dragging in scene not working So I have this problem where I try to instantiate prefabs as in this video for example. I can take instantiate one prefab to the scene, but if I try to instantiate a second one to the scene (whether it's with the same prefab or a different one), instead of creating an instance of the second prefab, it brings the first instance I had created to my mouse and I'm in position to move it by dragging it around. The only work around I have for this so far is to drop into the hierarchy instead of the scene (which works fine), but I have to carefully avoid the scene while dragging and dropping, otherwise the above described issue happens instantly. Am I doing something wrong, or is this a bug of some kind? EDIT I managed to reproduce the error in a consistent manner. I don't know why it happens, but it does every time. It doesn't involve code and it is very simple to reproduce (at least for me, perhaps not for you if you're not doing the wrong thing that I do...). I created a new project. I created a cube and a sphere. I turned them both into prefabs and deleted the original instances (they have the .prefab extension in my folder, so I am sure). I drag dropped the cube in, works fine. I drag the sphere in, and it appears as a cube which I have to position (by releasing the click), and my initial prefab instance of the cube is gone.


How to run code selectively only when a specific trigger collider has been hit I have 2 objects both with trigger colliders. The first object has only 1 trigger collider (imagine this to be a sword). The second object (a person) has multiple colliders. One is a non trigger collider (used for collision detection for walls, ground) and then multiple trigger colliders on different parts of the body (the purpose is for hurt box). Now when the sword hits the person, I want to only process code for those trigger colliders and to be able to detect which of those trigger colliders got hit (arm, leg, etc.). But the event only exposes a parameter hit for the other collider void OnTriggerEnter(Collider other) if (other.gameObject.layer LayerMask.NameToLayer(Constants.LAYER HITBOX PLAYER)) Run code here I want to run code only when certain trigger collider are hit, like for example, when the head is hit, or the body, etc. How do I get this info to be able to run conditional code on this method?


How can I scale object on one side only with a speed factor? using System.Collections using System.Collections.Generic using UnityEngine public class ScaleOneSide MonoBehaviour public float speed 1 float mfX float mfY Use this for initialization void Start() mfX transform.position.x transform.localScale.x 2.0f mfY transform.position.y transform.localScale.y 2.0f Update is called once per frame void Update() if (Input.GetMouseButton(0)) Vector3 v3Scale transform.localScale transform.localScale new Vector3(v3Scale.x 0.1f, v3Scale.y 0.1f, v3Scale.z) transform.position new Vector3(mfX transform.localScale.x 2.0f, mfY transform.localScale.y 2.0f, 0) transform.localScale new Vector3(v3Scale.x 0.1f, v3Scale.y, v3Scale.z) transform.position new Vector3(mfX transform.localScale.x 2.0f, 0, 0) transform.localScale Vector3.Lerp(transform.localScale, new Vector3(v3Scale.x 0.1f,0,0), speed Time.deltaTime) When using only this two lines it was working fine without changing the speed transform.localScale new Vector3(v3Scale.x 0.1f, v3Scale.y 0.1f, v3Scale.z) transform.position new Vector3(mfX transform.localScale.x 2.0f, mfY transform.localScale.y 2.0f, 0) But now I'm trying to add to the scaling a speed. I want when I press the mouse left button it will scale the object according to the speed.


How to disable spring joint in unity 3d How can I disable Spring joint in unity 3d, since disabling feature only available in 2d mode, I am not able to find any way to disable it via script


Unity 2D graphical glitch cuts sprite diagonally While making a game in unity, we found a graphical glitch that only happens on one of our mobile devices (a htc) where the screen will be oddly sliced by a triangle as shown in this image I've searched online but found no problem. We're using unity 2D, it only does it on the HTC but we have no idea why. The background is a 3D quad with a texture wrapped around it (so we can make it move with the character when the character is running, without having one large background). Any help would be greatly appreciated. Thanks


Is it possible to somehow change the collider points to match sprites during the animation in Unity? Is it possible to somehow change the collider points to match sprites during the animation in Unity? I am using the Unity built in animtion recording feature. I would like to change the points of some of my colliders as animation goes, while at the same time I am changing the respective sprites. I was not able to find any solutions so far. Any ideas how I could do that? I have a few attempts to overcome the problem. Create a few game objects with the different preset points for the colliders. The solution will work. But it is crazy hard to develop and maintain resources wise. I will have to spend an immense amount of time creating a separate game object with a collider for each frame. And also the maintenance will be very lame. Because I will need to add a wrapper around all the places where I access collider. So that the wrapper would return the currently enabled collider. I can buy the 2DColliderGen. But I do not want to spend money on that. And also it is not completely what I am looking for, because even with it I will have significant difficulties developing my animations, maintaining my game and extending it.


How to bounce the ball off a collider and destroying it using trigger? I am making a Breakout game. I have bricks with box colliders and the ball is a rigidbody2d with circular collider. I have applied the PhysicsMaterial2D on the ball with bounciness set to 1 so the ball is bouncing off the bricks as intended. Now I want to detect this collision in C so I could destroy the brick but I cannot enable the isTrigger property as it will disable the collisions in that brick. So, I am looking for a way to do that.


Unity setting rectTransform on an UI Image with a Vector3, do I need to convert coords? I am trying to build a menu with a cursor. I created the menu and that in the unity UICamera on the canvas. It looks great. I want the cursor to move so what I did was move the cursor by hand and record the values at each location I want the cursor to possibly be (see attached). The problem is later when I try to set the value to these via this pauseCursor.rectTransform.position new Vector3 ( 45f, 80.6f, 0) It fails and looking in the inspector again the x,y values are like 300, 800 or something. I am guessing I need a conversion I just am not sure where or how. Do I get the Ui camera reference and use the WorldToScreen?


Difference between 2 quaternions I need to patch an animation during LateUpdate. I'm rotating the "chest" bone according to the mouse delta. This is to mimic aiming a pistol. During this aiming, the "neck" bone should stay relatively still. As changing the chest bone's location rotation yaw automatically changes the "neck" bone's local yaw rotation, I store the chest bone's rotation BEFORE I apply a new rotation to it. Then I calculate the difference between the old and the new rotation. Then I apply this rotation yaw difference to the neck bone. The inspector gives me nice values to work with. When I inspect the rotation values by script, I get reprensations that I can not easily work with. Here is an example While the Inspector shows "15.4", the localEulerAngle shows "344.6". If I use "344.6", the neck rotation goes Berzerk of course. How should this be solved? For completeness, here is the entire void private void pHandle LateUpdate Aim() Vector3 nOldChestRotation Chest.localRotation.eulerAngles Fade old input before capturing new, so we don't dull the freshest data. float yawBlend Mathf.Pow(1.0f Aim yawInputFalloff, referenceFramerate Time.deltaTime) A Lerp toward zero is just the same as a multiplication by the blend factor. Chest yawRate yawBlend Accelerate by mouse movement over the past frame. (May need adjustment for display resolution). Chest yawRate Input.GetAxis("Mouse X") float yawDelta Chest yawSpeed Chest yawRate Time.deltaTime float offCenterYaw Chest currentYaw Chest yawCenter float fDesiredChestYaw Chest currentYaw yawDelta float fHeroRotation 0f if (fDesiredChestYaw gt Chest rotateRange) fHeroRotation fDesiredChestYaw Chest rotateRange we don't rotate the chest beyond the allowed "Chest rotateRange", so simply act like the user didn't move the mouse Chest yawRate 0 yawDelta Chest yawSpeed Chest yawRate Time.deltaTime else if (fDesiredChestYaw lt Chest rotateRange) fHeroRotation (Chest rotateRange fDesiredChestYaw) Chest yawRate 0 yawDelta Chest yawSpeed Chest yawRate Time.deltaTime If we're moving away from the center, slow down as we approach the edge. if (yawDelta offCenterYaw gt 0) float extremityYaw offCenterYaw Aim yawMaxRange yawDelta 1.0f extremityYaw extremityYaw this.transform.Rotate(0, fHeroRotation, 0) Ensure we never overshoot the allowed range. Chest currentYaw Mathf.Clamp(Chest currentYaw yawDelta, Chest yawCenter Aim yawMaxRange, Chest yawCenter Aim yawMaxRange) Vector3 nNewChestRotation new Vector3(Chest.localEulerAngles.x, Chest currentYaw, Chest.localEulerAngles.z) Chest.localRotation Quaternion.Euler(nNewChestRotation) float fChestRotationDifference nNewChestRotation.y nOldChestRotation.y the neck should not rotate with the chest. So I first counter rotate it against the new chest rotation, then rotate it a little towards the chest rotation Neck.transform.localRotation Quaternion.Euler(0, Aim NeckYaw fChestRotationDifference (fChestRotationDifference 0.5f), 0)


Why the skyline continues to stay on the same place and how to change this? I started my first Unity3D project and in this game main hero should be able to fly up passing clouds and then reaching open space but i faced with the problem. No matter how long and fast i am flying after takeoff the skyline continues to stay on the same place. Currently i'm going to rotate the main hero so that skyline would go down. But maybe someone can suggest me more common and better way to achieve the effect of leaving the Earth? I think it would be bad idea to post all my code here because there is a lot of code that does not relate to the topic. But i will try to explain what i'm doing now and i will show you short piece of code. I have global parent object and a main hero is added as a child to it. Then when as main hero moving up relative to the global object i start to rotate this global object around z axis so that gradually the main hero is looking to the sky. And for skyline i'm using procedural skybox. I hope this piece of code will explain better of what i'm doing now using UnityEngine using System.Collections using UnityEngine.UI public class PlayerController MonoBehaviour float gravity GameObject global main hero s parent Vector3 startHeroLocalPos start hero position relative to the global object public float degreesPerUnit 1.0f global object will rotate by this amount of degrees after the player has moved up by one unit void Start () global GameObject.FindGameObjectWithTag ("GlobalObject") startHeroLocalPos transform.localPosition void Update () float curAngle (transform.localPosition.y startHeroLocalPos.y) degreesPerUnit global.transform.rotation Quaternion.AngleAxis(curAngle, Vector3.back)


How should I account for the GC when building games with Unity? As far as I know, Unity3D for iOS is based on the Mono runtime and Mono has only generational mark amp sweep GC. This GC system can't avoid GC time which stops game system. Instance pooling can reduce this but not completely, because we can't control instantiation happens in the CLR's base class library. Those hidden small and frequent instances will raise un deterministic GC time eventually. Forcing complete GC periodically will degrade performance greatly (can Mono force complete GC, actually?) So, how can I avoid this GC time when using Unity3D without huge performance degrade?


How to instantiate new GameObject at position of old GameObject onAnimationComplete I have a GameObject that is a Farmer that plants Seeds. The Seeds will animate into Plants. Once that animation is complete, I'd like to replace my Seed with a Plant. This happens hundreds of times per game at arbitrary positions. I've tried this as something I built off of this question Unity detect animation 39 s end public class SeedScript StateMachineBehaviour SerializeField private GameObject seed override public void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) Destroy(this) animator.GetComponent lt TreeScript gt ().GrowTree(seed) Instantiate (tree, this.position, this.rotation) Obviously, this doesn't work at all. Doesn't even compile. I've also looked at these co routines https answers.unity.com questions 981948 statemachinebehaviour startcoroutine.html but again, I need to get position data from the animating object. Yes, I could just merge my Seed and Plant classes together, let's pretend I cannot do that and MUST instantiate some arbitrary new object at the position of another object on some animation completion.


Wheels not facing right direction when car faces different directions I am creating a real time multiplayer driving game in Unity. I am using google play's real time multiplayer service. I am having an issue where the wheels of the cars that are over the network are not facing the right direction. What I am currently trying to do is just add the calculated steering angle to the current rotation of that particular player's car, but for some reason the wheels face the wrong way and rotate incorrectly if the car is facing certain directions. Logically I thought what I have is correct. Basically for each wheel I use this code car.transform.rotation Quaternion.Euler(0, car.transform.rotation.y steerAngle, 0) So I find the rotation of that car and then I add the steer angle to it. Why wouldn't this work?


Coding style about collisions with geometry Let's say I'm writing 3D Pacman. I have "Dot" objects throughout my maze, that are structured as follows in the Inspector Dot (GameObject) Sphere w Collider When I run into the sphere trigger, I can trivially say "Get me your parent and check if it's a Dot" However, I hate baking in the knowledge that some spheres have parents that are Dot objects. If the trigger were on the Dot itself that problem would solve itself, as I could just call GetComponent(). What's a good programmatic style approach to finding out what logical Game Object actually owns the geometry you've collided with? I could add a Tag of "Dot" to the sphere but that's just a level of confirmation, I still would have to walk up to it's parent and check.


How can I launch Visual Studio via a double click on a C script in Unity? This is my first time using Unity and I am following the tutorial for the 2D RogueLike Game. Everythings seems to be working properly, apart that I cant get Visual Studio to launch, if I'm double click my c scripts. What I have tried so far Checked my preferences, that External Script Editor says "Visual Studio 2017" Reinstalled Unity and Visual Studio. Unity Version 2019.3.0a2 Personal Hope somebody can help me. Additional information After double click, nothing seems to be happening, even my mouse doesnt show a load icon When I create a new project, the bug (dont know if bug, or my fault) is still there. I can open the .sln file from my project in Visual Studio. Visual Studio can even autocomplete unity based code then, before it was a "miscellaneous file" and didnt autocomplete code like for example "Transform" or "Rigidbody2D".


Is There a Way To Keep Precision When Transforming GameObjects I've seen this issue before, but it's never been a particular issue for me until today. I have each "room" of a dungeon created with a class script that contains details of that room. During the process of building the dungeon, rooms may be mirrored or rotated. When I rotate the y axis, it updates properly the first time, going from 0 to 180, but if I mirror it back and forth, it begins to get very small variances away from true 0 and 180. Over time, this could impact some things. The code I'm using to do this is public void RoomMirror() transform.Rotate(0, (transform.localRotation.y 180) ? 0.0000f 180.0000f, 0) Mirror !Mirror Swap(ref east, ref west) I added the four places in the float to try to overcome this issue, but it doesn't seem to be making any difference. Thanks!


How can I spin a child capsule of a cube parent? I have a parent cube and to make it like a surface I had to change the rotation of the cube on the X to 90. and as a child, I added a capsule, and to make the capsule like standing I had to change the capsule X also to 90. The result is The reason I put the capsule child of the cube is that I want the capsule to move with the cube. The capsule rotation on the X is also 90 Then in a script at the top, I added speed and index variables for the rotation private int index 0 private int rotationIndex 0 In the Update RotateTo() And the method curvedLinePoints is a List private void RotateTo() var distance Vector3.Distance(capsule.position, curvedLinePoints rotationIndex .transform.position) if(distance lt 0.1f) rotationIndex Determine which direction to rotate towards Vector3 targetDirection curvedLinePoints rotationIndex .transform.position capsule.position The step size is equal to speed times frame time. float singleStep rotationSpeed Time.deltaTime Rotate the forward vector towards the target direction by one step Vector3 newDirection Vector3.RotateTowards(capsule.forward, targetDirection, singleStep, 0.0f) Draw a ray pointing at our target in Debug.DrawRay(capsule.position, newDirection, Color.red) Calculate a rotation a step closer to the target and applies rotation to this object capsule.rotation Quaternion.LookRotation(newDirection) The problem is that because the capsule is a child when I rotate the capsule it looks like the capsule changes its shape and not spinning around itself. If I remove ut the capsule from the prefab and will rotate it on its own it will spin fine but when it's a child of the cube the result is I tried before running the game to play with the capsule rotation in the editor in the inspector changing the Y and Z values and the result is like in this screenshot. but I want to spin it around itself but because it's a child of the cube it's not spinning but looks like it's changing its shape. The workaround I found is to create an empty GameObject at 0,0,0 and put both Platform and Capsule as a child of it. Then I added this part to the script above private void LateUpdate() capsule.localPosition transform.localPosition new Vector3(0, 1.4f, 0) This way the Capsule is following the Platform. The empty GameObject is just to put them both together. and for testing I just did in the Update capsule.Rotate(0, 10, 0) and it's working fine. Now I have to figure out how to make this rotation with the code in the RotateTo method.


Box collider has different behavior in 2 clients I'm new to Unity. I am making my first Game and faced with problem. I have a plane and 4 gameobject that has box collider surrounded this plane. there are a few spheres as players inside of the plane.I built the game. I run 2 instances of the game and add force to a sphere and send this force to other client through node server. But border reflection angle differs in 2 clients. I checked value of the force in 2 clients and that is the same. Any help would be appreciated.


2d Grid Generation (Unity C ) I am creating a simple program in Unity C that will generate a 2d grid using a 2d sprite prefab. I am stuck here, I don't know what to do. When ran, I receive an error. Assets Generator.cs(22,75) error CS0165 Use of unassigned local variable grid object' I am a beginner, so I'm not sure what to do. This is most likely a rookie mistake, so thanks in advance. using UnityEngine using System.Collections public class Generator MonoBehaviour public float Width 20 public float Height 20 public Transform grid object private GameObject , grid new GameObject 20,20 void Start () CreateGrid() private void CreateGrid() for (int x 0 x lt Width x ) for (int y 0 y lt Height y ) GameObject grid object (GameObject)Instantiate(grid object) grid object.transform.position new Vector2( grid object.transform.position.x x, grid object.transform.position.y y) grid x,y grid object


Adding Color to button after cloning public GameObject button public void Start() GameObject button1 Instantiate(button) as GameObject button1.transform.SetParent(canvas.transform, false) button1.transform.position new Vector3(7, 0, 2) I have cloned the button game object now want to add color to that game object how can i do it ?


Why don't objects far away from the camera experience floating point issues? In Kerbal Space Program, a space exploration game made with Unity, Floating origin technique is used to overcome the floating point precision issues. While in map view, the world (a scaled space with miniature celestial bodies) is recentered around the camera every frame so glitches don't occur when viewing unsafely distant planets. But when such planets are observed from an 'unsafe distance' (more than 10 000 units in scaled space), they're still rendered normally. Why don't floating point issues occur?


How can I reflect a point about a line in Unity? I am drawing a line using the line renderer in the following way public class MyLineRenderer MonoBehaviour LineRenderer lineRenderer public Vector3 p0, p1 Use this for initialization void Start () lineRenderer gameObject.GetComponent lt LineRenderer gt () lineRenderer.positionCount 2 lineRenderer.SetPosition(0, p0) lineRenderer.SetPosition(1, p1) From the image below, the line P0P1 is known and so is point A. How can a point B, which is the reflection of A about the line P0P1 be found?


Draw line inwards in Unity using Line Renderer Is there a way to draw the line inwards instead of from the center using Line Renderer in Unity? Another option would be to move the Vector points inwards by half the width of the line, but If I have a complex polygon how do I do it uniformly? EDIT Found this https stackoverflow.com questions 1109536 an algorithm for inflating deflating offsetting buffering polygons which may be useful


Unity How do I fix the players model rotation in a NetworkManager to spawn properly? How do I fix the players model rotation in a NetworkManager to spawn properly? I created a game with the NetworkManager code. Player Model is a cone I made and imported. all works fine but when the NetworkManager spawns the player model it is sideways. I have tried turning it in 3ds but the player remains sideways when it is spawned by NetworkManager on run, Ohterwise the model is fine in unity, and no matter how I rotate it, in or out of unity , The NetworkManager Rotates it. All other objects attached to the main object remain with proper orientation all, All other objects including instantiated ones appear properly.


What physics settings do I need to apply to make the pool game realistic? I want to create a pool game using Unity. I added the spheres as playballs and cubes as the walls. I added a rigidbody to all objects and Im able to do some basic collisions like in a pool game. My Question is What physics settings do I need to apply to make the pool game realistic? Right now, it's a bit weird. The ball does not bounce off the walls realistically and also the ball to ball collisions are not ok. Any suggestions?


How to implement Fog Of War with an shader? Okay, I'm creating a RTS game and want to implement an AgeOfEmpires like Fog Of War(FOW). That means a tile(or pixel) can be 0 transparent (unexplored) 50 transparent black (explored but not in viewrange) 100 transparent(explored and in viewrange) RTS means I'll have many explorers (NPCs, buildings, ...). Okay, so I have an 2d array of bytes byte , explored. The byte value correlates the transparency. The question is, how do I pass this array to my shader? Well I think it is not possible to pass an entire array. So what technique shall I use to let my shader know if a pixel tile is visible or not?


Setting SteamVR Camera Target Eye before SteamVR installed in Unity I'm writing a plugin that can be used in both VR and non VR projects. I have a Camera that is used to display UI containing some game info on a secondary monitor. My problem is that when the end user adds my plugin and then imports steam vr, this UI camera's Target Eye is set to "Both" by default. I can't have any SteamVR code in my plugin. But I can't adjust Target eye property of the camera without it. I just want it so that the camera doesn't change when a user imports SteamVR. I want it to always render to the main display (target eye none) So just to clarify, I have my plugin, written in a non vr project with a standard Unity camera. There is no Target Eye setting for this standard camera. User wants to use it in VR project, imports plugin into SteamVR Project Camera used to render UI gets automatically converted (wrongly) into SteamVR camera Defaults to Target Eye Both Need it to be Target Eye None At the moment to avoid users submitting countless bug reports, I have to provide warnings in like 6 places telling users to dig way into my built in prefabs to adjust this setting manually if they use SteamVR. It's not easy for new Unity users, and I want to make adoption as easy as possible.


Score does not increment by 1 in Unity I have made a simple code where once the player moves through the collider that acts as a trigger then Unity adds a score. However, it increases by increments of 8 and I am not sure why. using System.Collections using System.Collections.Generic using UnityEngine public class Game MonoBehaviour public int Score 0 void Start() Update is called once per frame void Update() private void OnTriggerEnter2D(Collider2D other) AddScore() void AddScore() Score


Unity Text Mesh Pro can not get referenced in VSCode I am using Text Mesh Pro in my Unity 2019.3.4f. The TMP works fine in unity, but in the code editor, Visual Studio Code, the TMP related things are marked with red wave underline, which means the VSCode could not get the reference of TMP. In my csproj file, the TMP reference exists, here are some related codes lt ProjectReference Include quot Unity.TextMeshPro.csproj quot gt lt Project gt e8ae9ed6 ed86 3de7 e777 7e6794b003b2 lt Project gt lt Name gt Unity.TextMeshPro lt Name gt ProjectReference Include quot Unity.TextMeshPro.Editor.csproj quot gt lt Project gt af8771c0 66d3 f01a 48b5 78951bce8a23 lt Project gt lt Name gt Unity.TextMeshPro.Editor lt Name gt My TMP works fine in every aspects, but there are code warnings in the VScode, quot could not fine the namespace of TMPro quot . Is there anyone know how to fix it?


How can I let the user choose his own background image? Dear Stackoferflow Fourm I would like to have a function in my Android Game Programming that allows the user to choose his own background image (I would like to let the user change the plane image) Unfortunately I have no idea how I could do that. If someone knows how to do it I would be very happy.!


List of Lists for sending paths from client to server? I have a client server scenario and I'm looking into distributed AI. I want the server to move x amount of ai characters around a map by pathfinding and then send the x amount of paths to the client which will apply each path to its corresponding AI character. This is for research purposes to see if this approach, by sending the new path of each server AI to the client AI for it to follow, is better than constantly sending a positional update across a network everytime a server gameobject moves slightly. I would like this X amount to range anywhere from 10 to 2000, a big ask i know, but i'll go into what I have atm. Atm I have this working for 2 AI characters and it can be expanded, but with my existing code it would mean an awful lot of copying and pasting! So on the server when the path is created it is sent to a script which can bundle it into an RPC an send it on its way public class GrabbingArrayFromUnitScript NetworkBehaviour public List lt Vector3 gt receivedArrays new List lt Vector3 gt () public List lt Vector3 gt receivedArrays1 new List lt Vector3 gt () ClientRpc void RpcPosFromServerToGoTo(Vector3 path, String name) if (name "SeekerPrefab") receivedArrays.AddRange (path) UnityEngine.Debug.Log ("Received") if (name "SeekerPrefab (1)") receivedArrays1.AddRange (path) UnityEngine.Debug.Log ("Received 1") public void PrintPath(Vector3 path) if (isServer) UnityEngine.Debug.Log("Send Array ...") RpcPosFromServerToGoTo (path, transform.name) UnityEngine.Debug.Log("Sent!!") So as you can see from the above if I wanted to add more AI characters in I would have to add more if statements to the RPC call, and if I wanted 2000 AI in that would be alot of copying. So what could I do here to reduce this code down? Would I use a list of lists? Any help would be greatly appreciated!


How do I determine the rotation of a Tile using Tilemap in Unity 2d? I want to know the rotation of the tile in C in order to do some logic on another object that is sitting on the tile. The rotation matters for the logic. I don't see anything except GetTileData in the doc, but that doesn't actually seem to "Get" the tile data. I could cast to Tile but not all tiles are Tile. Alternatively, I think I can get the rotation if I can get the GameObject for the tile but I have no idea how to do that either from a BaseTile. Anyone have any suggestions? Maybe I'm trying to do this wrong and I should make different tiles for each orientation or extend BaseTile or some other solution instead of trying to determine rotation. Any help or ideas would be greatly appreciated! Additional info When I inspect around in the Unity editor I see that the rotation is stored in Z in something called "Grid Selection" but I can't find a programmatic way of accessing that.


How to get the file location of missing sprite in unity? I accidentally moved some of my sprites and now I can't remember where they were originally. Now in Unity, it says missign sprite. So can't I get the location saved in scene file??? i.e. if it is referring to Desktop file.extension and I move it to Desktop files file.extension, can I get Desktop file.extension in Editor???


How to await player input using Coroutines How can I accept player input using Coroutines, pausing execution of Unity while the player has not yet provided input? It seems like a simple problem, but I can't seem to figure it out. Here is my latest attempt. In this program I want to do some logic and pause in the middle, continuing only when the player has inputted some data. Someone please tell me I'm on the right track O using System using System.Collections using System.Collections.Generic using UnityEngine public class InputTester MonoBehaviour int choice 1 valid choices for this example are 0 and 1 void Start() StartCoroutine(DoSomeLogic()) IEnumerator DoSomeLogic() print("Starting...") print("Awaiting your choice 0 or 1. ") yield return StartCoroutine(WaitForKeyDown(KeyCode.Alpha0) WaitForKeyDown(KeyCode.Alpha1)) how to combine these two into a single method that gives the player a choice? print("Continuing...") switch (choice) logic based on the choice IEnumerator WaitForKeyDown(KeyCode k) while (!Input.GetKeyDown(k)) yield return null SetChoiceTo(k) private void SetChoiceTo(KeyCode keyCode) switch (keyCode) case (KeyCode.Alpha0) choice 0 break case (KeyCode.Alpha1) choice 1 break StopAllCoroutines() how do I stop all the coroutines that accept player input? print(choice)


Why use Time.deltaTime in Lerping functions? To my understanding, a Lerp function interpolates between two values (a and b) using a third value (t) between 0 and 1. At t 0, the value a is returned, at t 1, the value b is returned. At 0.5 the value halfway between a and b is returned. (The following picture is a smoothstep, usually a cubic interpolation) I have been browsing the forums and on this answer I found the following line of code transform.rotation Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime) I thought to myself, "what a fool, he has no idea" but since it had 40 upvotes I gave it a try and sure enough, it worked! float t Time.deltaTime transform.rotation Quaternion.Slerp(transform.rotation, toRotation, t) Debug.Log(t) I got random values between 0.01 and 0.02 for t. Shouldn't the function interpolate accordingly? Why do these values stack? What is it about lerp that I do not understand?


Shadow Glitch on Mesh Stitches I use LWRP, one Directional Light and Hard Shadows with 1024 resolution. When I imported this super simple mesh from blender this happened What is this weird line on the stitch of the mesh and how do I fix it? I tried using Soft Shadows with higher quality but it did not help.


Problem with Input.GetKeyDown to set a counter in Unity multiple values in only one pressing Using Unity 5, I want to use have one keyboard key ("f") increase a counter when pressed. It means, using Input.GetKeyDown("f") function in a way that if "f" is pressed when the counter 1, then the counter is set to be equal 2. If counter was equal 2 when "f" is pressed, then counter is set to 3. However, it does not work properly it seems that Unity detects the key being pressed many times, no matter if it was only pressed once. See the code that illustrates the situation using UnityEngine using System.Collections public class TestingKeyGetRecursion MonoBehaviour int counter 1 void Update () if(counter 1 amp amp Input.GetKeyDown("f")) counter 2 Debug.Log(counter) if(counter 2 amp amp Input.GetKeyDown("f")) counter 3 Debug.Log(counter) if(counter 3 amp amp Input.GetKeyDown("f")) counter 1 Debug.Log(counter) void OnGUI() GUI.Label(new Rect(30, 10, 250, 20), "counter " counter.ToString()) As you can see in the console if you run the above example, the values are properly set into the counter variable and printed in the console. However, it happens several times in the same key hit and, in the end, the counter ends up equal as it started, i.e. equal 1. Can anyone please explain 1) why does the Engine behave like that 2) is there a way to solve such situation? I cannot substitute the counter with a bool variable and just do "counter ! counter" when "f" is pressed.


In Unity, how do I make text annotations appear when I mouse over GameObjects in playmode? How do I make text appear when I mouse over GameObjects in game? What is the Unity jargon for this? I'm assuming it's 'annotations'.


Am I experiencing a gimbal lock problem when rotating my cube? So I'm trying to build a simple mechanic where the player see's 3 sides of a cube at a time top, left and front(I called the front side "Right" in my code, due to the orthographic view). The player can click on the front side or left side of the cube to rotate the cube so that the side that was pressed moves and becomes the top face. I want to smooth animate the rotation. The red faces are the faces that the user can click on. My Logic seems to work quite well when I click on the left face (Rotating along the x axis), but doesn't seem to work well for the front right face(It usually works once and then does weird stuff on the next click, this is on the z axis) public class CubeRotator MonoBehaviour private const float STOP THRESHHOLD 0.1f private const float ROTATE AMOUNT 90f SerializeField, Header("Touch Quads Colliders") private Collider touchQuadLeft SerializeField private Collider touchQuadRight SerializeField, Space(10) private float timeToRotate private bool mustRotateLeft false private bool mustRotateRight false private float targetX 0.0f private float targetZ 0.0f private float xVelocity 0.0F private float zVelocity 0.0F int layerMask private void Start() layerMask LayerMask.GetMask("Touch Quad") void Update() ListenForTouch() RotateCube() private void ListenForTouch() if (Input.GetMouseButtonDown(0)) Vector2 touchPoint Input.mousePosition RaycastHit rayCastHit Ray ray Camera.main.ScreenPointToRay(touchPoint) if (Physics.Raycast(ray, out rayCastHit, 150f, layerMask)) if (rayCastHit.collider touchQuadLeft) mustRotateLeft true targetZ targetZ ROTATE AMOUNT zVelocity 0f else if (rayCastHit.collider touchQuadRight) mustRotateRight true targetX targetX 90f xVelocity 0f private void RotateCube() float zAngle transform.rotation.eulerAngles.z float xAngle transform.rotation.eulerAngles.x if (mustRotateLeft) zAngle Mathf.SmoothDampAngle(zAngle, targetZ, ref zVelocity, timeToRotate) if (Mathf.Abs(zVelocity) lt STOP THRESHHOLD) mustRotateLeft false if (mustRotateRight) xAngle Mathf.SmoothDampAngle(xAngle, targetX, ref xVelocity, timeToRotate) if (Mathf.Abs(xVelocity) lt STOP THRESHHOLD) mustRotateRight false transform.rotation Quaternion.Euler(xAngle, 0f, zAngle) Inspector Values I've tried several things, the only problem I can think of is, gimbal lock. Thanks in advance.


How can I assign a layer to tiles on an individual level? I've just started out with my first game in Unity. It's a simple 2D Platformer with a tile based level. When coding in the movement, I used the Physics2D.OverlapCircle() and an empty to check whether my player was touching the ground. However, I need to use a layer to make sure only the ground is detected. my code below fixed update used for physics calculations void FixedUpdate() right or left arrows being pressed float moveX Input.GetAxis( quot Horizontal quot ) Vector2 moveDir new Vector2(moveX playerSpeed, rb.velocity.y) rb.velocity moveDir update used for spacebar input and force void Update() if (Input.GetKeyDown(KeyCode.Space)) rb.velocity Vector2.up jumpForce Time.deltaTime is my circle overlapping any other colliders Collider2D collider Physics2D.OverlapCircle(feet.position, checkRadius, groundLayer) Debug.Log(collider) When I tried assigning layers to my tiles, I couldn't find a way to do it. I would be really grateful if anyone could show me how to, or if anyone can tell me a more efficient way to deal with jumping in a 2D platformer.


Add points to a prefab in Unity I have a prefab that looks like this I have created a couple of 'points' in the Hierarchy using 'Create Element' and I would like to attach them to the prefab, however drag and drop over doesn't work. Why is that?


How to publish a Unity desktop game without a security warning? When I build a Unity game as a Windows Desktop application, zip the folder, and upload the zip to itch.io, then anyone downloading the zip from itch.io and running the game gets a security warning from Windows. Is there a way to build the game in a way that will not show this warning?


How do I get a popup menu to block clicks from hitting UI elements beneath it? You can see in the picture that I have a Canvas with a popup menu in it. I just enable this, and it covers the main menu stuff. Clicks go through it and hit stuff in the main menu. I've tried adding an EventTrigger to the PopupRoot object, and adding an event to listen for PointerClick events, but it doesn't fire. EventTrigger trigger m popUpRoot.GetComponentInChildren lt EventTrigger gt () EventTrigger.Entry entry new EventTrigger.Entry() entry.eventID EventTriggerType.PointerClick entry.callback.AddListener((eventData) gt PopupClickBlocker((PointerEventData)eventData) ) trigger.triggers.Add(entry) I'm open to other suggestions. My current system is horrible button click events query the Popup to see if it's enabled or not, then return doing nothing if it is. This doesn't work for sliders very well, so I want to do this the right way.


Fade into scene in Unity SteamVR I am using this code below for a gradual fade into a scene next level in Steam VR (HTC Vive) The whole idea is to cover up the scene loading icon which is viewable for 3 4 seconds, and the default Steam landscape scene. The fade (to red) works fine BUT it comes in after the loading icon so this defeats the whole purpose of it. Is there any simple way to fix this? thanks public class NewFade MonoBehaviour private float fadeDuration 4f private void Start() FadeFromWhite() private void FadeFromWhite() set start color SteamVR Fade.View(Color.red, 0f) set and start fade to SteamVR Fade.View(Color.clear, fadeDuration)