null check vs. NullReferenceException: Object reference not set to an instance of an object

NullReferenceException: Object reference not set to an instance of an object

This is a major concept I still don’t get. I can’t assign it in the editor, but I might need to swap objects, so I think, I’ll do this:

if (leftHoldBone.GetComponentInChildren<LeftHold>().gameObject != null)
{
Destroy(leftHoldBone.GetComponentInChildren<LeftHold>().gameObject);
}

And I think, “There, if it’s null, it will just skip this function.”
So I am always confounded when I get the “NullReferenceException: Object reference not set to an instance of an object”

Because I’m like, “yeah, I told you if its null! Ignore it! but instead you throw an exception, and say, ‘hey, this is null!’” and I’m like “I know its null! that’s why I told you to ignore it!”

I don’t get it. I’ve never got it. What am I missing? What am I misunderstanding about a null check?

You’re checking if the component “LeftHold.gameObject” is NULL but if it doesn’t find a “LeftHold” component then it’ll return NULL so you’re doing “if (leftHoldBone.null.gameObject != null)”. Or maybe “leftHoldBone” is NULL etc.

The exception error tells you which line, column and which part.

Side Note: You seem quite happy grabbing components twice but know that it is work you’re doing twice and scale this over your project, it’ll be time spent doing stuff many more times than required. Ask for a component but place it in a variable and then check the variable. If it’s fine which should be in most cases, just use the variable. Don’t go asking to search for the component again.

1 Like

Thank you for the side note as well!

1 Like

To be clear about the above, when you say:

you are ONLY checking the .gameObject property, which can technically never be null except if someone has destroyed the underlying instance of the LeftHold script, in which you would never find it with GetComponent anyway.

When you write code like the above, that is hairy code.

If LeftHoldBone is null, you crash.

If there is no LeftHold script, you crash.

How to break down hairy lines of code:

http://plbm.com/?p=248

Break it up, practice social distancing in your code, one thing per line please.

the hairy code thing is actually kind of a new thing for me. I was experimenting, I never really liked it, but I thought maybe that’s why people like C#, because you can call anything from anywhere with enough dots and getcomponenets. But now I understand why I was right in the first place to avoid it.

Yeah, more than one dot in any single expression and you’ve become a test pilot with no parachute and a possibly un-airworthy aircraft.

Both the computer and your brain only do one thing at a time. Putting 27 things into one statement doesn’t change this. :slight_smile:

1 Like