Nullreference on mouseHit.collider.name using raycasting
I am writing a script for camera panning, now everything is working except I get a null reference exception on this line:
} else if (mouseHit.collider.name == null)
this is the code in some more context, the script is not finished yet
private void FixedUpdate()
{
mouseRay = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (mouseRay, out mouseHit))
{
Debug.Log (mouseHit.collider.name);
camCol = "" + mouseHit.collider.name;
} else if (mouseHit.collider.name == null)
{
camCol = "";
}
if (camCol == "")
{
transform.Translate (0, 0, 0);
}
if (camCol == "leftCam")
{
transform.Translate (-0.1f * panSpeed, 0, 0);
}
I only ask questions here as a last resort, any help would be greatly appreciated! Also, am I correct in thinking that the output of mouseHit.collider.name is a string?
Answer by jgodfrey · Apr 12, 2016 at 07:08 PM
This code is problematic:
else if (mouseHit.collider.name == null)
That's because "mouseHit" is an object. If it's null (as in your case), you'll get a null reference exception when trying to access properties of the object (collider) - simply because the object (mouseHit) doesn't exist.
The proper way to do this is:
if (Physics.Raycast (mouseRay, out mouseHit))
{
// here, the raycast hit something and mouseHit should be valid. Just access it as necessary.
}
else
{
// here, mouseHit will not exist (because the raycast did not hit anything) - don't attempt to access it!
}
And, yes, the mouseHit.collider.name will be a string.
$$anonymous$$akes sense, thanks! EDIT: Updated my code and it works great.