How to fix this null reference exception?

Hey people!

I’ve been working with the ‘Tile Based Map & Nav’ package with a honeycomb grid, and am trying to make a system that checks all nodes on the map (40x40, 1600 nodes), detects obstacles, and edits the properties of the neighbours of those objects.

This is what I have so far, but I’m completely stuck as to why it keeps giving me the same error. It’s one of the ‘null reference exception’ errors, referring to my variable ‘node’.

Here’s the code:

public MapNav theTileMap;

void setGiant () {
    Debug.Log("setGiant initiated");
    // run this class at end of each unit's movement

    float offsetY = 2f;
    RaycastHit hit;
    foreach (TileNode n in theTileMap.nodes) {
        if (Physics.Raycast(n.gameObject.transform.position, Vector3.up, out hit, offsetY * 4f)) {
            TileNode node = hit.collider.GetComponent<TileNode>();
            if (node.gameObject.layer > 20) {
                Debug.Log("Hit unit " + hit.collider.gameObject.name + "on layer " + hit.collider.gameObject.layer);
                foreach (TileNode n2 in node.nodeLinks) {
                    if (n2.IsDirectNeighbour(node)) {
                        Debug.Log("n2's name: " + n2.name);
                    }
                }
            }
        }
    }
    howLongDidItTake -= 2;
    Debug.Log("time it took: " + howLongDidItTake);
    countUp = false;
}

The ‘howLongDidItTake’ timer just shows exactly that, running through 1600 nodes I thought it would be neat to know how long it would take. It hits between 0.001 and 0.0005 seconds on average.

Thanks to anyone in advance who can shed some light on this problem.

Edit x4: Replaced the ‘quot&;’ with " marks… and added in the mysteriously-disappeared < TileNode> after the GetComponent line.

The error is on this line

TileNode node = hit.collider.GetComponent();

In the documentation it states “Returns the component of Type type if the game object has one attached, null if it doesn’t”. So it can return null first you should check that your node is not null before using it.

if (node != null && node.gameObject.layer > 20)

Secondly, I believe you are also using GetComponent() incorrectly by not specifying what type you are looking for. Try changing your code slightly to this and see if this works

TileNode node = hit.collider.GetComponent<TileNode>();

You raycast upwards and just guess that the object, what ever it is, has a TileNode script attached. You should either check if the hitted object has such a component or put all nodes in a seperate layer and use a layermask in your raycast.

It seems you already playing around with layers, so setup a layermask for the Raycast. This will even increase the performance when you ignore other stuff.