0
\$\begingroup\$

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 ?

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

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.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.