Press ‘R’ to Restart - Loading Scenes in Unity

Matej Marek
3 min readApr 23, 2021

--

In the last article, we have created the ‘Game Over’ behavior. This article will cover how to work with scenes and their management. We will do this by allowing the player to restart the scene whenever the ‘Game over’ text is shown.

First setup:

First, we have to go into the ‘Build settings’ of Unity > You can open this up by going into the ‘File’ > ‘Build settings,’ or by pressing the ‘Ctrl + Shift + B’ shortcut by default.

A ‘Build Settings’ window has opened for us. Here click on the ‘Add Open Scenes’ button to add all of your open scenes in the editor. This is important so that Unity knows what scenes you want to work with.

After clicking on the button, a scene should appear in the list. Notice the number which is shown in the right part of the window. This number indicates the ‘buildIndex’ number of each scene.

With the scene prepared, we have to create the actual text that will be shown when the game is over, which will inform the player about the possibility to restart the game. This is done similarly as we did in the previous article - and here is the result that I am going with!

Onto the code!

Now that we have everything set, it is time to code in the behavior. Today, we will make use of the ‘Game Manager,’ which we created some time ago - so let’s go ahead and open up the ‘GameManager’ script.

First up, we need to add a new namespace to the script, allowing us to work with scenes.

Now, all we need to do is check when the game is over, and when the player presses the ‘R’ button, the scene will be reset, and the player can play the game again from the start.

Since we currently have only one scene active in our game, we reference the currently active scene and load it from the start.

Now only one small detail remains, and that is also to show the ‘Restart_game_text’ when the game is over - and we do this by creating a reference for the text in the ‘UIManager’ script and setting it active the same way as we do with the ‘Game_Over_text’.

And that is all! - Now, whenever the player dies, he can simply click the ‘R’ button to reset the level and keep on playing till the end of times.. or more likely, until he falls asleep.

But that is it for now, thank you for reading and feel free to follow me for more articles - and as always, good luck and see you next time!

--

--

Matej Marek
Matej Marek

Written by Matej Marek

Aspiring and eager beginner Unity developer

No responses yet