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:


[pastacode lang=”java” manual=”Vector3%20inputPos%20%3D%20Input.mousePosition%3B%20%2F%2F%20or%20maybe%20Input.GetTouch(0).position%0AinputPos.z%20%3D%201f%3B%20%2F%2F%20or%20some%20other%20distance%2C%20just%20don’t%20leave%20it%20with%200f%0AVector3%20worldPos%20%3D%20myCamera.ScreenToWorldPoint(inputPos)%3B%20%2F%2F%20converting%0AGameObject%20myPrefabClone%20%3D%20GameObject.Instantiate(myPrefab%2C%20worldPos%2C%20Quaternion.identity)%20as%20GameObject%3B” message=”Example” highlight=”” provider=”manual”/]

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.