Quick Guide to Unity’s Scene Loading
Loading Scenes in Unity
Objective: Provide the ability to restart the game
If you have been following my progress with this Space Shooter, the project is now at the stage where it makes sense to allow the game to restart. This introduces the concept of Scenes.
Scenes are where we work with content in the Unity editor. You could have one scene for the whole game or use them as logical containers. For example, have a scene that represents a level like in Angry Birds and each scene is a different level.
Restarting a scene
In the current project, when the player loses all their lives, the game still continues but there is no player on the screen. This is where we should restart the game and to do this we reload the scene so all the game objects in the scene reset to their original settings at the beginning.
For this, we will create a new game object called GameManager with its own script. When the player has no more lives, it will communicate to the GameManager script by calling GameOver and the game will put a message up on the screen for the player to press ‘R’ to restart.
Create a new empty game object in the scene and name it GameManager
Create a new GameManager script and add it to the GameManager game object.
Open the GameManager script and add a new flag (a variable that is a boolean) called _isGameOver that will store if the game is over or not.
Create a public method that can be called to set the flag to true, indicating the game is over.
In the Update method, check the isGameOver flag, and if it is true and the ‘R’ key is pressed, have it reload the current scene.
Notice how we reload the scene by using the SceneManager object. To get access to this, we need to include the SceneManagement library. Add this to the top of the script with the other using statements.
In the UIManager, we have the existing public method UpdateLives, it checks when the lives are equal to zero then it will call a GameOverSequence.
The GameOverSequence is the one that communicates to the GameManger to update the game over the flag. It then displays the restart message on the screen and flicks the Game Over text as shown below.
We now added a Restart Game feature by reload the Scene.
If you enjoyed reading this article give me a Clap, also if you would like to see more, “Follow” me, so you may be notified of future releases. You may also send me a message if you need any further help.