Variable Null Error without triggering conditional 'if null'

                    NodeDS<HexDS> adjNode = new NodeDS<HexDS>();

                    if(adjNode == null)
                    {
                        Debug.Log("assignment failed");
                    }

                    adjNode.assignValues(a, h, (a.region.terrainType.movementCost + n.cost));
// .assignValues just gives values to the instance created.

The above code gives a “NullReferenceException: Object reference not set to an instance of an object” at the last line, but I just assigned it and it doesn’t trigger the if statement. Is there an obvious error I’m missing or are there cases where an non-null variable can trigger a NRE?

                    NodeDS<HexDS> adjNode = new NodeDS<HexDS>();
 
                    if(adjNode == null)
                    {
                        Debug.Log("assignment failed");
                        adjNode.assign(a, h, (a.region.terrainType.movementCost + n.cost));
                    }

In one line you ask… is it null, so you know if it appears outside that context, then it could be null… just move it into the context

Thanks, but I don’t understand how can adjNode be null? I just assigned a new instance to it. If it did fail I should see the debug message right before the error, right?

sorry, I totally misread that…

You are right… try this…

                    NodeDS<HexDS> adjNode = new NodeDS<HexDS>();
 
                    Debug.Log(a);
                    Debug.Log(h);
                    Debug.Log(n);
                    
                    adjNode.assign(a, h, (a.region.terrainType.movementCost + n.cost));

Unfortunately they all read as expected. h is null though, would that cause a problem? I need adjNode’s h value to be null and nothing in .assignValue would prohibit it.

Edit: If I change h to be non-null, error still happens.

if n is not null and a is not null… is a.region, or a.region.terrainType ?

1 Like

Yeah, that was it! I had an issue with the constructor that occasionally didn’t assign terrain type right and it ended up null. I can’t believe I didn’t see it. Its obvious in retrospect, sorry.