Lecture: Singleton Scorekeeper - NullReferenceException

In Summary: The issue is a race condition where the LevelManager is loading the ScoreKeeper object in the Awake() method, but the ScoreKeeper ManageSingleton() method is deleting the object that the LevelManager has loaded, thus losing the reference.

Here is my cleaned up solution to the issue. I deleted the Awake() method from Level Manager, and added a method that loads the ScoreKeeper object only when necessary (when the LoadGame() method is called.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class LevelManager : MonoBehaviour
{
    [SerializeField] float sceneLoadDelay = 2f;
    ScoreKeeper scoreKeeper;

    void findScoreKeeper()
    {
        if(scoreKeeper == null)
        {
            scoreKeeper = FindObjectOfType<ScoreKeeper>();
        }
    }

    public void LoadGame()
    {
        findScoreKeeper();
        scoreKeeper.ResetScore();
        SceneManager.LoadScene("Game");             
    }

    public void LoadMainMenu()
    {
        SceneManager.LoadScene("Main Menu");
    }

    public void LoadGameOver()
    {
        StartCoroutine(WaitAndLoad("Game Over Menu", sceneLoadDelay));
    }

    public void QuitGame()
    {
        Debug.Log("Quitting");
        Application.Quit();
    }

    IEnumerator WaitAndLoad(string sceneName, float delay)
    {
        yield return new WaitForSeconds(delay);
        SceneManager.LoadScene(sceneName);
    }
}

2 Likes