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))
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?
So the exception is in which line exactly? The one where you use Camera.main?
Answer by syclamoth
Apr 19, 2012 at 07:14 AM
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;
Ray vRay = myCam.ScreenPointToRay(Input.mousePosition);
That worked perfectly. Thank you.
Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.
The best place to ask and answer questions about development with Unity.
To help users navigate the site we have posted a user guide.
If you are a new user, check out our FAQ for more information.
If you are a moderator, see our Moderator Guidelines page.
We are making improvements to UA, see the list of changes.
For troubleshooting common problems with Unity 5.x Editor (including Win 10).
Answers and Comments
6 People are following this question.
Ray camera to Terrain goes Wrong.
Camera/mouse movement issues "almost but no dice"
Raycast Object Selection
Unity Android Movement Problem
Raycast from Character to Mouse Position?