Loading Scenes in Unity

Jason Schneider
4 min readAug 1, 2021

Now that we have a functioning GAME OVER screen, how can we restart the level? For this we need to load the current scene.

Since we currently have no reference to this scene, we will first need to create a scene index. This is accomplished by first making sure our scene is saved, then by left clicking on File, then left clicking on Build Settings and then left clicking on Add Open Scenes and then exiting, as below:

The added scene is automatically given the index of 0 (being first scene).

Now that we have our scene indexed, we can now add a Text object to our canvas and name it Restart_text. Next we can change the text to Press “R” to Restart Level and adjust the size, color and position of it to our liking. Since the position I have chosen is fairly central I will anchor the text to the middle and center. I will also set the horizontal and vertical overflow to overflow.

After setting this up, we need to have the text shown when the game is over. This is done by adding the following to our UIManager script:

Saving the script and jumping back into Unity we can drag the Restart_text into the newly created Restart Level Text field in the Inspector. Jumping back into the UIManager script we can add:

to the Start() method.

Then, we need to add the following to the GameOverSequence() method:

Saving the script and jumping back into Unity (I will set lives to 1 in inspector) and then running the game gives:

Awesome, now that we have that working, we need to code when the “R” key is pressed and the game is over (since we don’t want the “R” key to be pressed during the game) the scene is loaded.

Even though it would be possible to put this coding into the UIManager, it doesn’t make sense to; scene loading is a part of the game. Therefore, best practice is to create a script called GameManager to handle all things Game related.

Now we need to add a reference to the GameManager script by adding the following to our UIManager script:

Then, we can add the following into the Start method:

The last part of code to add to the UIManager is:

Save the script and then jump into the GameManager script and add:

Serialized so we can tell in inspector if active.

Now we can add the GameOver method as below:

In order to load scenes in Unity, we need to add another namespace as below:

And finally, we can add the below to the Update method:

Which gives:

--

--