Unity reporting coding error even when code copied from documentation!?!

Hi Folks.

I am stumped. I am trying to make an object move left and right across the screen following the position of the mouse. Using code from the Unity documentation, I wrote this script:

    void Update () {
        //Position bat at X of mouse.
        Vector2 MouseCoords2D = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
        Vector3 MouseCoords3D = new Vector3();
        MouseCoords3D = Camera.main.ScreenToWorldPoint(new Vector3(MouseCoords2D.x, 1, 1));
        MouseCoords3D.y = 1;
        MouseCoords3D.z = -26.5f;
        this.transform.position = MouseCoords3D;
    }

No errors reported in Microsoft Visual Studio. But when I run it in Unity, it doesn’t work and the console just posts over and over again, this error message:

NullReferenceException: Object reference not set to an instance of an object

I’m stumped!! Can anyone give me some advice please?

What line is getting the null reference?

What that means is some variable your trying to use, isn’t set to anything yet (or has been unset in some cases, but not this one I don’t think).

On the code above, it says it’s line 5.

I’m not sure I see which variable is getting the null ref in this situation, so perhaps put in a “Debug.Log (MouseCoords2D);” to test each variable just after assignment (the line after they are set) and when it gives you a null ref at the debug statement, you’ve got your problem narrowed down to what specific variable is null.

Most likely, you don’t have a camera in your scene that is tagged as MainCamera. That is just a guess since the other variables shouldn’t be null. So double check your camera in your scene.

1 Like

I ran the debug of MouseCords2D, I don’t have a null. How do I check that my camera is set to main?

I got it. No more error message but now while the bat move from size to size as I move the mouse, it only moves a few millimetres side to side instead of across the screen.

I think I see what you’re going for here.

Give this a try inside your Update() function:

transform.position = new Vector3(Camera.main.ScreenToWorldPoint(Input.mousePosition).x,0,0);

Don’t forget to change 0,0 to your Y/Z restraints respectively.

Got it working, thanks very much to all for the help!

1 Like