A NullReferenceException issue

_gameManager = GameObject.Find("WinTrophy").GetComponent<GameManager>();

The above line of code is odd, as it gives me a NullReferenceException error saying “Object reference not set to an instance of an object”. I have confirmed that there is a GameManager _gameManager, an object called WinTrophy and a script called GameManager.

That my friend is a “hairy line of code.” Fix it and you will find what is null.

How to break down hairy lines of code:

http://plbm.com/?p=248

And when you do, you will find which one of those is actually null because the computer does not lie.

The answer is always the same… ALWAYS. It is the single most common error ever.

Don’t waste your life spinning around and round on this error. Instead, learn how to fix it fast… it’s EASY!!

Some notes on how to fix a NullReferenceException error in Unity3D

  • also known as: Unassigned Reference Exception
  • also known as: Missing Reference Exception
  • also known as: Object reference not set to an instance of an object

http://plbm.com/?p=221

The basic steps outlined above are:

  • Identify what is null
  • Identify why it is null
  • Fix that.

Expect to see this error a LOT. It’s easily the most common thing to do when working. Learn how to fix it rapidly. It’s easy. See the above link for more tips.

This is the kind of mindset and thinking process you need to bring to this problem:

Step by step, break it down, find the problem.

    private GameManager _gameManager;
    private GameObject _GameManager;
        _GameManager = GameObject.Find("WinTrophy");
        if (_GameManager == null) {
            Debug.Log("It broke in part one");
        } else {
            _gameManager = _GameManager.GetComponent<GameManager>();
        } if (_gameManager == null && _GameManager != null) {
            Debug.Log("It broke in part two");
        }

After getting the message “It broke in part one”, I was/am still confused. As I mentioned earlier, there are no spelling mistakes relating to objects and variables, and it was the first block of code to run in void Start(). I commonly use code like* _GameManager = GameObject.Find("WinTrophy"); in my scripts, so I don’t think there is an error that I couldn’t find.

*Only code that I change are the variables/object.

How about just finding the GameManager itself with FindObjectOfType() ? The name kinda implies there’s only one, correct?

This is another one of those classic reasons NOT to use GameObject.Find(), which must have been written a million times. For some unspecified reason it’s failing (yet again) above. :slight_smile:

Or else just use a singleton:

Simple Singleton (UnitySingleton):

Some super-simple Singleton examples to take and modify:

Simple Unity3D Singleton (no predefined data):

Unity3D Singleton with a Prefab (or a ScriptableObject) used for predefined data:

These are pure-code solutions, do not put anything into any scene, just access it via .Instance!

If it is a GameManager, when the game is over, make a function in that singleton that Destroys itself so the next time you access it you get a fresh one, something like:

public void DestroyThyself()
{
   Destroy(gameObject);
   Instance = null;    // because destroy doesn't happen until end of frame
}

I can’t implement the FindObjectOfType because the game object I am calling is a prefab, and the scripting API says “::ref::.FindObjectOfType will return no Assets (meshes, textures, prefabs, …)”

It’s not going to return something out of your project folder. It will return something in your scene.

Also, many of these Find calls require active GameObjects, so make sure that your objects are active if the call requires it.

Well, there is one part of Unity’s example I don’t get. In (typeof(Camera)), what is Camera reffering to? (Ref.: Unity - Scripting API: Object.FindObjectOfType)

Its nearly sure “WinTrophy” is not active in the scene and the Find returns null

I have already figured that out. Please read the entire thread. Currently my problem is that I need to find how to use FindObjectOfType to see if that fixes my problem.

Camera is the Camera class and Object.FindObjectOfType will also only return active objects

“Returns the first active loaded object of Type”

Can you please clarify on the “Camera is the Camera class” bit?

well, can you please clarify what is NOT clear on it?

in the line

Camera cam = (Camera)FindObjectOfType(typeof(Camera))

all 3 “Camera”-s are the same, just representing the Camera class in unity. first to declare the cam variable, second time to cast the returned object and third to get the type. its all the same (and its really stupid to be honest, it shouldnt need the cast and the typeof but unity works in mysterious ways). If you click the red underlined word it actually takes you to the Camera class

https://docs.unity3d.com/2019.4/Documentation/ScriptReference/Camera.html

was your prefab instantiated?

Camera is mentioned 3 times, and cam is mentioned once. I have no clue what these are referring to, so I don’t know which relevant variables/names I should replace them with.

Yes it was.

I see. I believe it should be

GameManager _gameManager = (GameManager)FindObjectOfType(typeof(GameManager));

or

GameManager _gameManager = (GameManager)FindObjectOfType<GameManager>();

and then check if its null

private GameManager _gameManager;
_gameManager = (GameManager)FindObjectOfType(typeof(GameManager));
        if (_gameManager == null) {
            Debug.Log("The game manager could not be found.");
        }

Thanks, but after testing, I still have a problem. The above code is two excerpts of my script. After running the code, I got the message “The game manager could not be found.”, which indicates that _gameManager is null, which doesn’t fix my original question, why is this code broken? Also, the message still appeared after I commented some other code that was giving me an error, so nothing wrong there.

its not the code is broken, its the instantiation must have failed so the gamemanager does not exist or is inactive in the scene. otherwise this would have to find it… when you run the game, check in the editor hierarchy if the wintrophy is there, its active, and the script is attached to it.

Type t:GameManager into the hierarchy search bar. This should highlight all gameobjects with a script of type GameManager on it.

If there is no objects in the scene with a GameManager on, or the object is disabled, that would cause the NullReferenceException.

Yeah, you are right. After my search turned up empty, I tracked down the problem to a missing DontDestroyOnLoad. Thanks!

1 Like