Null reference exception while raycasting.

I am simply trying to detect when a mouse is hovering over my box with a collider on it. However, it infinitely loops the same bug until the game crashes: NullReferenceException: Object reference not set to instance of object (at line 12). Here is the code:

function Update () {

	var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
	var hit : RaycastHit;

	if (Physics.Raycast (ray, hit, 100)) {
		Debug.DrawLine (ray.origin, hit.point);
		Debug.Log ("Raycast hit : " + hit.collider.gameObject.name);
	}
}

Any help would be appreciated!

That should be at line 3, this is an excerpt of the code.

I do have a camera, but should the camera be named main? or tagged as main? or in the main layer?

Got it, the camera needed to have the MainCamera tag. Wow is it laggy though!

you could try using a corutine to execute the check every 5 or 10 frames, the code in the update all the time could be harsh on the performance.

1 Answer

1

the only issue I can think of on line 3 is that maybe you don’t have a main camera :smiley:

Yeah I got it, my camera wasn't tagged as MainCamera. It seems to run into an infinite loop now anyway, but at least it isn't throwing up errors. Maybe I need to use FixedUpdate.