Search code examples
c#unity-game-enginesingletonnullreferenceexception

Unity - Why is my Singleton throwing a NullReferenceException when I re-load the scene?


I am facing an issue with a NullReferenceException in my code. I've created a LevelManager script to manage the different scenes of my game. Inside this file ScoreKeeper object is called. This ScoreKeeper is managed by a Singleton pattern to ensure a connection between the different scenes. Everything worked so far, until I tried to call the ResetScore method (when launching a new game (to avoid starting the game from the previous score)).

What I've already done :

  • Ensure a ScoreKeeper prefab is available in each Scene

enter image description here

  • Ensure the Awake() method is called

enter image description here

  • Manage the Singleton Pattern

enter image description here

Everthing worked perfectly when switching from from GameOver Scene to MainMenu Scene, but the bug appear when trying to load the Game Scene

Below is a screenshot of the object's list before trying to reach the Game Scene :

enter image description here

I really don't understand why this issue appear as a ScoreKeeper is well visible in the DontDestroyOnLoad section :(

Here is the error message that pop's up :

enter image description here

Thanks in advance for your clues


Solution

  • You are misusing the singleton pattern.

    The correct use would be this:

    In ScoreKeeper

    public class ScoreKeeper : MonoBehaviour
    {
        public static ScoreKeeper Instance { get; private set; }
    
        private void Awake()
        {
            if (Instance != null && Instance != this) // if we are the instance this is fine
            {
                Destroy(this);
                return;
            }
    
            Instance = this;
            DontDestroyOnLoad(this);
        }
    }
    
    

    Then when accessing it, don't hold on to a reference, just do this each time.

    ScoreKeeper.Instance.ResetScore();
    

    Your error was occurring because LevelManager's reference was somehow becoming null, likely because loading into the game made the original ScoreKeeper delete itself due to the error in its awake logic.

    This should now be safe either way... but perhaps best not to hold on to a singleton instance reference anyway, or you could forget it's a singleton not a normal variable.

    Also important to note. You Must set your singletons to run first in the Execution Order or you will run into problems trying to access them.