Intro to Scene Management, and Restarting the game
Last article we created a Game Over Screen overlay that gets activated when our Player’s Lives get down to 0. But we’re infinitely stuck in this state until we stop and start the Game again within Unity.
The Player doesn’t have this luxury, so we’ll have to create a way for them to restart the game. This leads us to our first introduction to Unity’s Scene Management. Which then creates a full Game Loop!
Player’s Instructions
The first step is to let our Player know that they can restart the Game by the press of a button. So, we’ll create some text to go along with our Game Over Screen:
Get a reference to it in our UIManager script:
And make sure it gets activated along with our GameOverScreen() function:
Can’t forget to link our Restart_text in the Canvas’ Inspector either!
Now our Restart Text appears as planned when our Player loses all their lives. But it doesn’t have any functionality, yet.
Creating a Game Manager
In most games, you’ll have a Game Manager that handles various things relating to the Game in general. Like Scene Management in our instance.
We’ll create an Empty Game Object called Game_Manager:
And also create a GameManager script:
Notice that it gets it’s own special icon? That’s because it is so common in building games and handles important aspects, thus very deserving of an icon to stand out from other scripts!
First inside the script, we’ll create a new private bool _isGameOver and a new public function to turn this bool to true:
Inside our Update function we’ll write in the following code:
Loading (or reloading) our Game (Scene)
We will fill in the pseudocode very soon, but first we have to add a new namespace within the GameManager script:
And now to make sure we can access our scenes properly, we have to jump into our Build Settings for the project.
Since we only have the 1 scene for now, we can click on Add Open Scenes and you can see that our Game Scene was added to the Scenes in Build section!
Now we can access our scene in two ways.
- By using the Scene Index
- By using a string value
Which you choose is up to you. But remember with string values you need to write the scene name EXACTLY as it appears.
Now when our _isGameOver bool gets set to true and we press the ‘R’ key, our game will reload to it’s starting state! Back to ground zero.
In the UIManager script
We’ll create a reference to our GameManager, initialize, and null check:
This allows us to call our GameOver() function from our GameManager, switching our _isGameOver bool to true!
Complete! Ladies and Gentlemen, we have a self-sustaining Game Loop! Time to celebrate by double-checking it works for about 10 minutes and replaying your game… WITHOUT STOPPING IT IN UNITY.
In the next article we’ll create a Main Menu, adding to our Scene Management skills, and making our game feel a little less like a demo!