Same NullReferenceException doesn't go away when I play the game through a couple times

This was just glossed over at the end of the lecture, but I have the same exact issue and it won’t go away. In fact, I can trigger it from the Start Menu screen every time I hit the Start button.

Hi,

Your post is a bit cryptic for anyone who hasn’t just been through that section, but I think, from memory, the issue will be your GameSession singleton code. The singleton approach used in the course is less than ideal, but you can get around the issue slightly by adding one line of code to disable the duplicated GameObject.

private void SetUpSingleton()
{
	if(FindObjectsOfType(GetType()).Length > 1)
	{
		gameObject.SetActive(false);    // add this line
		Destroy(gameObject);
	}
	else
	{
		DontDestroyOnLoad(gameObject);
	}
}

You should also check that the GameObject(s) that need to exist are created in the very first scene.

If the issue doesn’t relate to the above, then please provide more details which will help identify the problem.

Hope this helps :slight_smile:

Thanks Rob, and apologies for the lack of clarity. This was the line that was causing the error:

FindObjectOfType<GameSession>().ResetGame();

And this is the error: NullReferenceException: Object reference not set to an instance of an object
Level.LoadGame () (at Assets/Scripts/Level.cs:21)

I tried pasting in the Singleton solution and that didn’t work.

But then while writing this I figured it out. I didn’t have the GameSession object in my Start Scene. doh!

Pays to read the error.

Thanks for your quick response.

Cheers!

1 Like

From memory, it wasn’t added to the Start scene in the course, as the main Game scene was the primary focus of most of this section, with the Start and Game Over scenes added later.

But yes, in most cases where you are using a singleton pattern for this type of activity you’ll most likely want to have it on one of the scenes which loads first, after that, any duplicates should be destroyed (or better still, not created in the first place).

I’m glad you can move forward again with the course :slight_smile:

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms