I'm trying to Add raycast shooting to my player but when I get the Vector2 mouse position it give this error

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

This is my code

   Vector2 mousePosition = 
         new Vector2(Camera.main.ScreenToWorldPoint(Input.mousePosition).x,

How can i fix this ?

  • 2
    \$\begingroup\$ You sure it's not Camera.main that's null? \$\endgroup\$
    – Ben
    Mar 24, 2015 at 16:13
  • \$\begingroup\$ sory i didnt understand? \$\endgroup\$
    – hash
    Mar 24, 2015 at 16:15

1 Answer 1


Camera.main will be null if you don't have a camera in your scene with the tag MainCamera.

If you don't want to tag the camera, you can't use Camera.main but you can specify the Camera script you want to use. Something like:

GameObject cameraObject = GameObject.Find("MyCamera");
Camera myCamera = cameraObject.GetComponent<Camera>();
 Vector2 mousePosition =
                 new Vector2(myCamera .ScreenToWorldPoint(Input.mousePosition).x,
                 myCamera .ScreenToWorldPoint(Input.mousePosition).y);

Though, it's easier to just tag your main camera.

  • 1
    \$\begingroup\$ Sure. Remember to completely read your error messages. Further, it's super quick to attach the debugger and inspect your variables at run time, that'll give you a lot more flexibility to see what all the values are in your code and quickly debug issues like this. \$\endgroup\$
    – House
    Mar 24, 2015 at 16:27

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .