Scene Loading — Restarting our game
A little background before we dive in here.
Our game prototype has just one scene, but this will not be true for all but the most basic games.
Unity has built-in functionality for scenes that we will make use of.
Specifically, we are interested in the LoadScene() method of the SceneManager.
Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all submissions, we do…
“Scene management at run-time.”
Unity - Scripting API: SceneManagement.SceneManager.LoadScene
Suggest a change Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all…
“Loads the Scene by its name or index in Build Settings.”
We’ll be using the basic LoadScene() method, but keep in mind the warning Unity gives us here:
“Note: In most cases, to avoid pauses or performance hiccups while loading, you should use the asynchronous version of this command which is: LoadSceneAsync.
When using SceneManager.LoadScene, the scene loads in the next frame, that is it does not load immediately.
This semi-asynchronous behavior can cause frame stuttering and can be confusing because load does not complete immediately.
Because loading is set to complete in the next rendered frame, calling SceneManager.LoadScene forces all previous AsyncOperations to complete, even if AsyncOperation.allowSceneActivation is set to false. To avoid this, use LoadSceneAsync instead.”
Alright, let’s get started!
We’re going to create a new empty game object for our Game Manager code and add a GameManager script to it.
In our GameManager script we are going to add a using statement for Unity’s Scene Management code library, a Boolean value to track our game state, and a new GameOver() method which simply sets our new Boolean value to true.
In the Update() method we’ll check for the “R” keydown event and make sure _isGameOver == true before loading our scene.
For this code to work, in the Unity Editor, click “File” than “Build Settings” and add the current scene.
You’ll notice in the top right it adds an index number for the scene of 0.
When we check the name of our current scene in the Project folder, we see it is “Game”.
Now, the code in our if statement of the Update() method makes use of this.
We can load based on scene name, or even based on scene index.
Triggering the GameManager — GameOver() method from Player script
We’ll add a variable for our GameManager in our player script.
In the Unity editor, we drag and drop the Game Manager onto our Player script component.
In our LoseLife() method, we do a null check and make the call to our GameManager script and use its GameOver() method.
Since GameManager is likely to be used later on in our game from the player script for any number of reasons, let’s go ahead and check the null status immediately in our Start() method and log it to console.
Now we can restart our game after the player loses all lives.