Use Mouse or Touch position in World Space on Unity 3d

I recently got this little problem on Unity 3d. I was trying to instantiate a Prefab at the input coordinates in world space but, even using myCamera.ScreenToWorldPoint(myInputPosition), I was unable to do that.

What I discovered after a quick search is that if you pass a Vector3 with 0f in z value you’ll always get the same position for your cloned Prefab: the position of your camera.

So, to get rid of this little problem, you just need to add some distance (z) to the Vector3 that you’ll pass to the myCamera.ScreenToWorldPoint function … like this:


Vector3 inputPos = Input.mousePosition; // or maybe Input.GetTouch(0).position
inputPos.z = 1f; // or some other distance, just don't leave it with 0f
Vector3 worldPos = myCamera.ScreenToWorldPoint(inputPos); // converting
GameObject myPrefabClone = GameObject.Instantiate(myPrefab, worldPos, Quaternion.identity) as GameObject;

That’s it!

Join the conversation


Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.