Ignore NullReferenceException error?

I get a nullref. error when i use a raycast which checks if it is colliding with a wall.

Here is the code:

if (Physics.Raycast(transform.position,Vector3(0,0,-1),cast_col_bck,ray_dist_bck))
    {

        if(cast_col_bck.collider.gameObject.transform.parent.name == "wall")
        {
            Destroy(gameObject);
        }

    }

I think this happens when the raycast is not colliding with anything. If that is the case i dont really care about the error is there a way to prevent this?

Your problem is this:

if(cast_col_bck.collider.gameObject.transform.parent.name == "wall")

  • cast_col_bck - the RaycastHit from the Raycast and is guaranteed to be set.
  • .collider - the collider of the object that was hit and because the raycast hit, it is also guaranteed to be set.
  • .gameObject - every component must have a GameObject so this is also guaranteed to be set.
  • .transform - every GameObject has a Transform so this is guaranteed to be set.
  • .parent - This may or may not exist.
  • .name - every GameObject has a name, even if it is an empty string.

The object you hit doesn't have a parent, you can ignore the exception, but the best solution is to not generate one. Also, you may not realize this, but RaycastHit has a transform, meaning that you can save yourself several of your references by using `cast_col_bck.transform.parent.name`.

To avoid your exception causing condition, you would simply check for the thing that is causing your exception like so:

if(Physics.Raycast(transform.position,Vector3(0,0,-1),cast_col_bck,ray_dist_bck)
   && cast_col_bck.transform.parent
   && cast_col_bck.transform.parent.name == "wall") Destroy(gameObject);

or better still, if you know that your "wall" is the root of the hierarchy that you are looking for, use Transform.root which will never return null like so:

if(Physics.Raycast(transform.position,Vector3(0,0,-1),cast_col_bck,ray_dist_bck)
   && cast_col_bck.transform.root.name == "wall") Destroy(gameObject);

To ignore an exception, you would do something like

try{
    somethingDangerous();
}
catch(e : Exception) {
    Debug.LogError(e.Message);
}

If the raycast wasn't colliding with anything then Physics.Raycast would return false and it wouldnt even hit the nested if statement.

If I had to guess based off this code snippet.. probably whatever your Raycast is hitting, you are then going out and trying to grab its parent which it might not have and thats why you got the null reference error.

Anyways, in order to ignore exceptions you need to "catch" them by setting up try/catch blocks and handle them there.