Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

unity3d - In Unity (C#), why am I getting a NullReferenceException and how do I fix it?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Explanation

In C# generally, this is caused by referencing a field that hasn't 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 doesn't 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, you're trying to reference something that doesn't exist.

Solutions

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.

  1. 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.

  2. Looking at the GameObject, make sure you've assigned everything in the inspector that should be assigned.

  3. If everything has been assigned, run the game with the GameObject that threw the error selected. It's possible that you have something in Awake() or Start() that's negating the reference, and you'll see the inspector switch to None.

Image of two Unity inspector fields with nothing assigned

  1. 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 isn't fixing your issue, Unity's own page on NullReferenceException, and for C# generally, there's a more in-depth explanation of NullReferenceException in this answer.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...