Loading Scenes in Unity

Andrea Zilio
4 min readMay 1, 2021

--

Once a user looses all lives the current game is over. But what if the player wants to restart?

We are going to allow the player to restart using the ‘R’ key. Doing so means we need to reload the scene.

Lets first add a simple text object to the canvas to inform the player of this option. Make sure the top left tick box in the inspector is unchecked, so that it won’t display at the start.

Here is what it looks like, once we have adjusted the font and aligned it in the scene.

We then need to let the UI Manager know it exists. Thus we add a variable with a SerializeField so that we can assign the object in the script.

And the assignment in Unity, in the UI Manager script on the canvas.

Now we can add the restart text to our code.

It is common practice to manage the state of the game with the game manager.

To create a game manager we create an empty object called “Game_Manager” in our scene and a script. The script is attached to the Game_Manager.

The only task of the game manager right now will be to allow the user to restart the game if it is over.

Thus we create a boolean variable _isGameOver with a SerializedField. We then create a method to set the variable to true.

We now need to tell the game to reload the scene when the ‘R’ key is pressed and the _isGameOver is true. To work with scenes we need to add the Unity.Engine.SceneManagement;

We also need to add the current scene to our build settings. Go to File -> Build Settings and add the open scene.

We can now also see that our game scene has the ID of 0.

So let’s implement the logic. Our pseudocode goes like this

//if the Key R is pressed AND _isGameOver is true
//then load the scene 0

How this it look in code? Here we go:

But how does the GameManager know whether the game is over or not. We need to add reference handle to the UI manager script:

private GameManager _gameManager;

and then use a GetComponent to allow the UI manager script access the game manager script. As allways it is good practice to check if the component, here the game manager script is there.

What remains is to let the Game Manager know that the game is over by calling

_gameManager.GameOver();

from our game over sequence:

We can now go back to Unity and test it….

When we hit the ‘R’ key our game restarts.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Andrea Zilio
Andrea Zilio

Written by Andrea Zilio

Passionate Game Developer and Learning Expert. I love to create games and interactive experiences using Unity, Articulate, C#, JavaScript, PHP, HTML, CSS.

No responses yet

Write a response