About NullReferenceException Errors

So far i have always understood that NullReferenceException Errors basicly mean that there is no “Valid path” to what you try to acces/reference to. Usually this meant for me that I just forgot to put a reference for something but things like Awake orders going wrong has happend as well. During this lecture however I got one when I left the “GridDebugObject” in my hierarchy that i should have removed. It was a easy fix but i don’t really understand how this could have been leading to a NullReferenceException Error.

A NullReferenceException happens when you are trying to access something on an object that has no reference. With “when I left the “GridDebugObject” in my hierarchy that i should have removed” I suspect you have removed all uses of it in code, but did not remove the actual object from the scene. This is where your NRE comes from. The GridDebugObject expects you to set a grid object, and it tries to access this object in every update. If you did not set this grid object, you will get NREs because the grid object contains a null reference

protected virtual void Update()
{
    textMeshPro.text = gridObject.ToString(); // <- if you didn't set gridObject, you'll get a NRE
}
1 Like

Yup exactly you can think of objects as paths, so objectA.myField would mean you go through objectA to access myField. If the variable for objectA is set to null then you cannot reach myField and you have a NullReferenceException.
I made a really nice video on my process for solving NullRefs How to Fix NullReferenceException in C#! - Code Monkey
First step is identifying what is null, then you need to figure out where that variable should have been set. Maybe it’s a reference that should be dragged in the editor, maybe it’s another object that should have some reference, etc.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms