How do you use the ScreenToWorldPoint for receive the real mouse position ?

I find a lot of questions and answer about this but i haven’t finished to understand. I have this code but i dont know why don’t work…

public class mouseposition : MonoBehaviour
{

    public Vector3 worldPos;
    public Camera cameraOne;

    void Start()
    {

    }

    void Update()
    {

        if (Input.GetMouseButtonDown(0))
        {
            worldPos = cameraOne.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0.0f ));

        }
    }
}

I watch another place where puts camera.main or other things but sometimes (and in this case) say in the console:

NullReferenceException: Object reference not set to an instance of an object
mouseposition.Update () (at Assets/minichibi/script/partialscript/mouseposition.cs:20)

My question is what is the code that can I use to have the global mouse position (x,y). Z dont worry, i don’t need. What change or a funtional code if it is the case.

Thanks a lot :slight_smile:

You need to specify SOME value for the z coordinate that is not zero. The Z coordinate of the parameter defines a distance from the camera, so a distance of zero always results in the camera’s position, wherever that may be in the world (regardless of the x,y parameters!).

cameraOne.nearPlane might be a better value to use than 0.0f, but without some more details about what you want to do with this position, I can’t be sure of that.