So I’m at the part where I coded in for the score to reset after loading the game. But then I get this error
NullReferenceException: Object reference not set to an instance of an object
LevelManager.LoadGame () (at Assets/Scripts/LevelManager.cs:18)
And this is my level manager script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class LevelManager : MonoBehaviour
{
[SerializeField] float sceneLoadDelay = 2f;
ScoreKeeper scoreKeeper;
void Awake()
{
scoreKeeper = FindObjectOfType<ScoreKeeper>();
}
public void LoadGame()
{
scoreKeeper.ResetScore();
SceneManager.LoadScene("Game");
}
public void LoadMainMenu()
{
SceneManager.LoadScene("MainMenu");
}
public void LoadGameOver()
{
StartCoroutine(WaitAndLoad("GameOver", sceneLoadDelay));
}
public void QuitGame()
{
Debug.Log("Quit the Game");
Application.Quit();
}
IEnumerator WaitAndLoad(string sceneName, float delay)
{
yield return new WaitForSeconds(delay);
SceneManager.LoadScene(sceneName);
}
}
Basically the script is telling me that I cant reset the score at line 18 because my ScoreKeeper object doesnt exist. But when I check the hierarchy, I can still see the ScoreKeeper game object under DontDestroyOnLoad. I’m not entirely sure why this error pops up. I can still load the main menu, but I cant go into the Game menu from the Game over screen or from the Main Menu because it gives me this error.
And this is my ScoreKeeper script in case there’s something wrong there
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ScoreKeeper : MonoBehaviour
{
int score = 0;
static ScoreKeeper instance;
void Awake()
{
ManageSingleton();
}
void ManageSingleton()
{
if(instance != null)
{
gameObject.SetActive(false);
Destroy(gameObject);
}
else
{
instance = this;
DontDestroyOnLoad(gameObject);
}
}
public int GetScore()
{
return score;
}
public void ModifyScore(int value)
{
score += value;
Mathf.Clamp(score, 0, int.MaxValue);
Debug.Log(score);
}
public void ResetScore()
{
score = 0;
}
}
What could be causing this error?