Loading Scenes in Unity and C#

So let’s say our Player was unfortunate and just got a Game Over screen. What next? Our game doesn’t know what to do but I’m sure it’s a possibility that the Player may want another go at it.

To create the ability to restart the game if we get a Game Over, firstly we need a new UI GameObject with a Text component.

We can then get a reference to it and enable it at the appropriate time, in this case, at the end of the Game Over routine within our UIManager script.

We’ll also want to have a bool we can switch that turns true at the very end of our timed routine.

Now that the UI Display is all set up, we need to look at how to actually restart the game. To do this, we simply need to reload our current scene. When we do this, everything will revert back to it’s original state.

At the top of our UIManager script, we will need to add the namespace that allows us to access the Scene Management code library —

Then, in our UIManager’s Update method —

We can check our state bool and if that is true, check for the specified key press.

Alternatively —

Check both at the same time.

You’ll notice two different uses of the method. This is because it will take either a string or integer reference for the scene to load.

The string reference is the name of the scene in your project —

If there is only one scene in your game, the default integer reference for that scene is always ‘0’.

If you have multiple scenes in your project, you can find out the integer reference in the build options for your project — (File -> Build Settings…)

Manipulating available scenes

Here you can organise your scenes, adding from your project window, removing them, disabling/enabling their use and you can also drag them around to change their order in the list. The number to the right of the scene is the integer value required with the method for that particular scene.

A UK based Unity Developer with a passion for gaming and coding