#NullReferenceException in if statement that checks for null

1 messages · Page 1 of 1 (latest)

low bramble
#

The exception is thrown on the if statement's line. I know for certain that both "block" and "block.GetComponent<BlockHandler>()" aren't null thanks to Debug.Logging them. I know that the null thing is the "surroundings[whatIsDown]", but I'm quite baffled as to why it would throw a NullReferenceException just for accessing a null value in an array and checking if it is, indeed, null. The array is also initialized and usable so that's not it either. Any help?

private void CheckDown()
{
    foreach (Transform block in transform)
    {
        if (block.GetComponent<BlockHandler>().surroundings[whatIsDown] == null)
        {
            //do stuff
        }
    }
}
low bramble
#

sorry I got it
for some reason in the //do stuff section I was instantiating another object and it put it as a child of this one so it bugged since that new one didn't have a block handler component
still kinda weird but at least I know what's happening

clever gulch
#

There can only 2 things be null here: GetComponent<BlockHandler>() and surroundings.
Technically, block could be null as well, but that would mean that transform has a null child, and Unity would catch that and not return it when iterating children.
So either you forgot to attach a BlockHandler instance to one or more of the transform's children, or any of the BlockHandler instances you do have does not have its surroundings initialized.

Ideally, you should not be exposing surroundings but encapsulate it, to catch stuff like this. And I would recommend to use TryGetComponent as well, to be sure that a given component exists, before you access it.

low bramble
#

block handler was the problem