# Input.mousePosition gives a NullReferenceException

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,
Camera.main.ScreenToWorldPoint(Input.mousePosition).y);


How can i fix this ?

• You sure it's not Camera.main that's null? – Ben Mar 24 '15 at 16:13
• sory i didnt understand? – hash Mar 24 '15 at 16:15

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.

• 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. – MichaelHouse Mar 24 '15 at 16:27