- Home /
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?
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;
// later
Ray vRay = myCam.ScreenPointToRay(Input.mousePosition);
Your answer
![](https://koobas.hobune.stream/wayback/20220613070510im_/https://answers.unity.com/themes/thub/images/avi.jpg)