- Home /
Help with fixing NullReferenceException
Hello, During runtime I get an obnoxious amount of NullReferenceException error from this line
if(hit.transform.gameObject.tag != null){
I know why this is, its because the gameobject does not exist, how would I check to see if something exists without referencing it? Thanks
Answer by Bunny83 · Dec 10, 2013 at 09:11 PM
I guess that your "hit" variable is a RaycastHit which should be related to a Physics.Raycast call. "hit" is only valid when Physics.Raycast returns true. Without the code around this line you posted we can't say what's wrong.
If it's really this line i just guess that hit is not initialized and hit.transform is null. The tag of a gameobject usually can't be null. If it has no tag it's usually an empty string.
Answer by StormSabotage · Dec 10, 2013 at 09:12 PM
Is it a raycast? try this:
RaycastHit hit;
Vector3 direction = Vector3.forward;
float distance = 1.0f;
if(Physics.Raycast(transform.position, direction, out hit, distance)){
if(hit.collider.tag != null){
}
}