x


Before updating to Windows 10 you may need to return your Pro license. More information here

Raycast an Object to the mouse position

The following lines of code give a Null Exception Error:

         RaycastHit vHit = new RaycastHit();
         Ray vRay = Camera.main.ScreenPointToRay(Input.mousePosition);
         if(Physics.Raycast(vRay, out vHit, 1000)) 
         {
             Debug.Log("OK");
             Screen.showCursor = false;
         }

I did some research and realize that there has to be a main camera (which is the first one enabled). I only have one camera enabled but went ahead a made a script to enable the "main" camera. This line of code still does not work, and I don't know why...

Can there be another reason for a Null Reference?

more ▼

asked Apr 19, 2012 at 07:06 AM

avatar image

babanathie
35 14 12 16

So the exception is in which line exactly? The one where you use Camera.main?

Apr 19, 2012 at 07:18 AM senad
(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

The 'main' camera is actually a pretty fuzzy definition. What 'Camera.main' actually does, is return the first active camera tagged 'MainCamera'. If you have a camera, but it doesn't have that tag, it won't work!

I recommend that you create a public variable in your script to which you can attach the camera in the editor. This way you can be sure that not only is it the right camera, it won't ever create a null-reference exception.

 public Camera myCam;

 // later

 Ray vRay = myCam.ScreenPointToRay(Input.mousePosition);
more ▼

answered Apr 19, 2012 at 07:14 AM

avatar image

syclamoth
19.4k 24 46 157

That worked perfectly. Thank you.

Apr 19, 2012 at 07:19 AM babanathie
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x5883
x3485
x1646

asked: Apr 19, 2012 at 07:06 AM

Seen: 12379 times

Last Updated: Apr 19, 2012 at 07:19 AM