Hi Everyone,
Newbie here.
After the programming changes made in this lesson, I’m getting a ‘NullReferenceException: Object reference not set to an instance of an object’ error and the error points to this line in the Level.cs script:
FindObjectOfType<GameSession>().ResetGame();
The entire script reads as follows:
public void LoadGame()
{
SceneManager.LoadScene("Game");
FindObjectOfType<GameSession>().ResetGame();
}
I went through Rick’s video two additional times and I’m pretty sure that my coding matches what he did.
The only time the error appears shows is when the game is started from the top from the ‘Start’ scene.
It doesn’t happen if the game is started from the ‘Game’ scene or from the ‘Game Over’ scene.
It doesn’t happen if the game is continued from the ‘Start’ scene…In other words, I don’t get the error if I lose the game, get to the ‘Game Over’ scene, click on ‘Main Menu’ to get back to the ‘Start’ scene and, from there, click on ‘Start’. That works fine.
Again, the only time the error appears is when the game is initially started from the ‘Start’ scene.
So, thinking about it, I decided (maybe wrongly) that the problem might be that, when the games is first started, the GameSession object doesn’t exist. And so the line of code
FindObjectOfType<GameSession>().ResetGame();
is trying to reset an object that doesn’t yet exist.
So I changed the LoadGame() method to this:
public void LoadGame()
{
int numberOfGameSessions = FindObjectsOfType<GameSession>().Length;
if (numberOfGameSessions >= 1)
{
SceneManager.LoadScene("Game");
FindObjectOfType<GameSession>().ResetGame();
}
else
{
SceneManager.LoadScene("Game");
}
}
With this change, the error is gone and everything seems to be working fine.
So here are my questions:
- Am I even vaguely correct in my assessment of the problem? Or did I somehow just luck out with my ‘solution’?
- And, if I am correct in my assessment, why do I appear to be the only person having this issue?
- Is it possible that the Unity version I’m using (I’m pretty late to the game - I taking this class in 8/2021 and am using Unity version 2020.3.16f1) could have something to do with this?
Thanks in advance for any insight…