unity3d – In Unity (C#), why am I getting a NullReferenceException and how do I fix it?
In C# generally, this is caused by referencing a field that hasnt been initialized. For example, if you have a field
public List<GameObject> items and you later call
items.Add(foo) without first doing
items = new List<GameObject>(), then you are trying to add an item to a list that doesnt exist.
However, in Unity specifically, this is most frequently caused by forgetting to set a reference in the inspector. When you create a new component and add a field
public Transform destination, then you most likely are intending to assign a prefab in the inspector. If you forget, youre trying to reference something that doesnt exist.
If you double-click on the error message in the console window, Unity will (with a few exceptions) highlight the GameObject in the hierarchy that threw the error, and open your code editor and highlight the line of the script where the error occurred.
If you are using any of the
Find-like methods to get the GameObject, be sure that the GameObject is active, otherwise
Find-like methods will return null or may return the wrong GameObject. If you need the GameObject to be inactive when it is found, you need to use a different way of getting a reference to the GameObject than using a
Find-like method to find the GameObject directly, such as having the component register with a Manager-type class.
Looking at the GameObject, make sure youve assigned everything in the inspector that should be assigned.
If everything has been assigned, run the game with the GameObject that threw the error selected. Its possible that you have something in
Start()thats negating the reference, and youll see the inspector switch to
Pay attention to the return types of methods you use to modify objects. For example, if you call
GetComponent()or anything similar on an object and the component is not found, it will not throw an error. It will just return null. This can easily be handled with a line like:
if(thing == null) //log an error, or do something to fix the reference else //do what you wanted to do
That should cover the most frequent Unity-specific causes. If that still isnt fixing your issue, Unitys own page on NullReferenceException, and for C# generally, theres a more in-depth explanation of NullReferenceException in this answer.