What is a NullReferenceException?

In this article, we explore what a compilation error, a stack trace, and a NullReferenceException are and how to solve them. This is for the very beginning of your programming adventure. We've all been there once, so let me help you :-)

For experienced programmers, some things are so very obvious that sometimes they don't think it needs to be explained. Yet for a newcomer, these are the first hurdles to overcome.

This is a step-by-step tutorial. It assumes you already have Unity and a Code Editor installed and a new project created.

Let's create a script

To explain anything about coding we need some code. Let's create a script. To do that right-click inside the Assets folder and then choose Create > C# Script.

Unity will ask you for the name of the script. Please name it "CodingAdventure".

Now double-click the script file. Your code editor should start automatically. Usually, that is the "Visual Studio Community Edition for Unity" (Link). It looks like this:

Please make sure the name in the script (marked green) matches the name of the file. While this is not strictly necessary it is a very healthy convention to follow.

What is a Compilation Error?

Okay, the script we created has no errors. But we are here to learn about these so we will deliberately add one. Please copy and paste the script below into yours (replace everything).

using UnityEngine;

public class CodingAdventure : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        MethodWithError();
    }

    void MethodWithError()
    {
        Debug.Log("If you hit play then you should see this message in the console.")
    }
}

Once we switch back to Unity we will see this:

This is a compilation error. It means there is something in the code that the computer does not understand and it tries to tell you what it is. Sadly the computer is very pedantic and cares about every single character.

So, that's a very cryptic message. There is a lot of information to decipher in there. We need to break it apart. There are five bits of information stored in that single line of text.

Assets\CodingAdventure.cs(13,86): error CS1002: ; expected

In total this message tells us that in the file CodingAdventure.cs at line 13 at position 86 there should be a ";". If we look at that line we notice that there is none.

Once we have added the ";" we save the file and then we go back to Unity. Now, everything should work as expected. If we hit the play button we will see the message in the console.

Hint:  If you double-click the error in the console then it will open VisualStudio and jump to the line with the error ;-)

What is an Exception?

There are two big groups of errors a script can have. The first are "compilation errors", like the one we explored above. Compilation errors mean the text in your script file could not be converted to code.

The other big group of errors are "runtime errors". They are called runtime because they happen while your program is running. If a game crashes while playing then that is due to a runtime error.

If such a runtime error happens it is a common strategy to bundle up all the information about why and where it happened and give it back to the user for analysis. This information object is called an exception. Not all programming languages use exceptions, but C# does.

This process of "giving the exception object back to the user" is called "throwing an exception". You can tell Unity to pause execution if an Exception has been thrown.

Exceptions are also logged in the console as errors. Here is one of the most famous exceptions in Unity, the NullReferenceException.

An exception object usually contains multiple pieces of information:

What is a Stack Trace?

Before we can explore what a stack trace is we first need some code that throws an Exception. Please copy and paste the script below into yours (replace everything). 

The script tells a story:

  1. It is a dark gloomy night. We are approaching a house.
  2. We knock on the door. No one answers.
  3. We peek through the keyhole because we want to find out if someone is home.
  4. We see people inside and we count them.
using UnityEngine;

public class CodingAdventure : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        ApproachHouse();
    }

    void ApproachHouse()
    {
        Debug.Log("It is a dark night. We are approaching the house.");
        KnockOnDoor();
    }

    void KnockOnDoor()
    {
        Debug.Log("Knock on door.");
        LookThroughKeyhole();
    }

    void LookThroughKeyhole()
    {
        Debug.Log("We are looking through the keyhole.");
        CountPeopleInside();
    }

    void CountPeopleInside()
    {
        string[] people = null;
        int numberOfPeopleInTheRoom = people.Length;
        Debug.Log($"We see {numberOfPeopleInTheRoom} people.");
    }
}

Don't forget to save it after pasting the code in.

If you hit play then you will see this.

If you click on the red line with the exception you will notice that there is some extra information shown below in the console, the stack trace.

Let's go through the stack trace.

The first line is the exception name and message. So far so good, we already know that.

Each one of the other lines stands for one method that has been called. If you look at the script from above then you will see that Start() calls ApproachHouse() which calls KnockOnDoor() which calls LookThroughKeyHole() which then finally calls CountPeopleInside().

Within each line, we have multiple pieces of information. First the class name (CodingAdventure), then the method name (CountPeopleInside), then the script filename (CodingAdventure.cs), and finally the line number (32).

There is something odd about how the lines are ordered. They are backward. The line with Start() is last and CountPeopleInside() is first. Why is that?

This is done because most of the time we only want to know which line caused the error and that is the most recently executed line of code (the last in time). That's why stack traces are usually shown in reverse order. If ordered backward then the first line is where the error is, how convenient.

Hint 1:  If you double-click the exception in the console then it will open VisualStudio and jump to the line where it was thrown ;-)

Hint 2: The blue parts are links. If you click on those they will take you to that line in your code editor.

What does Null mean and what is a NullReferenceException?

Null is used by many programming languages as a name for a missing value or a value that represents nothing. Think of it like the zero in numbers. It also represents the absence of anything, it's just nothing.

If you have read about exceptions above then you are already familiar with the NullReferenceException. This means that while running your program at some point a value was null where it should not have been. If you then try to access that null value it will throw a NullReferenceException.

How to fix a NullReferenceException?

As we have learned Null stands for the absence of any data. Now how do we fix it?

The steps are always the same:

  1. Find out what is null:
    Use a Debugger or start by calling Debug.Log() on every single variable in the line that threw the exception.
  2. Find out why it is null (the tricky part)
    Once you know what is null try to go back in time (use the stack trace) and find out why, see below.
  3. Make sure it is not null or handle the null case (aka fix it).
    Sometimes null actually is a valid outcome of an operation. Make sure your code is prepared for that.

If you have followed the tutorials above then you should have a script that throws a NullReferenceExcpetion at line 32. If not then please copy it from the "What is a Stack Trace?" section above.

Let's look at the line that threw the NullReferenceException:

int numberOfPeopleInTheRoom = people.Length;

Okay, I can not see anything wrong here. All we do is call the Length property of people. Could it be that something is wrong with the people variable? Let's add a log line above, like this:

Debug.Log("People: " + people);
int numberOfPeopleInTheRoom = people.Length;

This yields the following result:

The people variable is logged as nothing. Hint: null values are logged as an empty string "", thus nothing is visible in the console. Now we know what is null, but why?

Let's use the stack trace. It tells us that the exception originated from the CountPeopleInside method.

The method looks like this:

void CountPeopleInside()
{
    string[] people = null;
    Debug.Log("People: " + people);
    int numberOfPeopleInTheRoom = people.Length;
    Debug.Log($"We see {numberOfPeopleInTheRoom} people.");
}

Aha, there we have it. In the very first line of the method it says "people = null".

string[] people = null;

It seems we have forgotten to fill the people array with actual people. Let's fix that. Replace the line with:

string[] people = { "Paul", "Mary" };

If we run the program now then it is working. Notice that the people are logged as a string array (System.String[]).

And that's it.

Recommendations

I hope you liked this little introduction to error codes. Here are some assets that may be useful to you. If you get one of them then some of the money will go towards funding this project. Thank you.

Disclosure: This text may contain affiliate links, which means we may receive a commission if you click a link and purchase something that we have recommended. While clicking these links won't cost you any money, they will help fund this project! The links are created by Unity and Partnerize (Unity's affiliate partner).

Did you know that if you join the Unity Newsletter you will get 25% off of your first Asset Store purchase? ➔ Join the Unity mailing list

Related Articles

Let the AI write the code

AIs have been all the rage for a while now. And rightfully so. Language AIs like ChatGPT are powerful tools and they are here to stay.
Read article ..

List of handy tools for Windows

Being a developer is hard work. Here is a list of tools that will help you out in a tricky situation.
Read article ..

How to ask developers for help

Asking for help can be hard. Here are some tips and tricks on how you will get the support you need.
Read article ..