I am stuck with this issue. What happens is: If I comment out the scoreKeeper.ResetScore(); on Script 2, I can play the game and the buttons (Play, Replay) work as intended, however the score is not reset after the game over screen has been switched back to the game screen, and even after choosing to play from the main menu. If I leave that single line of code in, both buttons dont work anymore and I am given the error “NullReferenceException: Object reference not set to an instance of an object
LevelManager.LoadGame () (at Assets/Scripts/LevelManager.cs:19)” I don’t know what to do. I was an inch away from finishing the course
Somebody help please!
Script 1
using UnityEngine;
public class ScoreKeeper : MonoBehaviour
{
int score;
static ScoreKeeper instance; //static persists through all instances of a class
void Awake()
{
ManageSingleton();
}
void ManageSingleton()
{
if(instance != null)
{
gameObject.SetActive(false);
Destroy(gameObject);
}
else
{
instance = this; //this indicates this version of the audio player.
DontDestroyOnLoad(gameObject);
}
//If we are the first ScoreKeeper to come along, first if statement is false and we will set
// ourselves as the instance of the ScoreKeeper, if not the first, selfdestruct to keep a singleton.
}
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;
}
}
Script 2
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 = FindFirstObjectByType<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()
{
Application.Quit();
}
IEnumerator WaitAndLoad(string sceneName, float delay)
{
yield return new WaitForSeconds(delay);
SceneManager.LoadScene(sceneName);
}
}