How to find the accurate z coordinate for the point where mouse is touched?

I want to spawn a cube at a point where mouse is touched. Here’s the code that I am using to convert screen coordinates to world coordinates:

var spawnPos:Vector3 = Camera.main.ScreenToWorldPoint(Vector3(touchPos.x, touchPos.y, Camera.main.transform.position.z + distance from origin));

This would always give me the same z value of spawnPos irrespective of touch position. However, in reality z coordinate should vary if the y coordinate of touch changes.

I’m not sure what you are doing with your last parameter in the Vector3 you pass to ScreenToWorldPoint(). This value should be a distance in front of the camera plane. Given your code you will get different ‘z’ values if the camera is moved. Regardless of your code you will get different ‘z’ values if the camera is not axes aligned. So if your camera is angled, the points generated will be parallel to the camera plane, not the world axes.