Objective: Implement a method to load/reload scenes in Unity.
A Scene file is a level. Inside, it contains the objects of your game, the environments, obstacles, and decorations. You will need to load a scene to advance to the next level or reload the scene if you want to restart the level.
In this tutorial I am going to show you how to restart the scene with an input after a game over.
To begin we will want to notify the player that they can press a key to restart the game. Create a UI text element, anchor to the bottom and set the font large to easily be read by the player and position below the player.
Create an empty object and label this Game_Manager and make a script called GameManager. You will notice the icon for this is in the shape of a gear, that is just a default setting.
Game Manager: is responsible for managing the state of the game, is the game over, is the player still alive, how many enemies there are in the game, that makes it the location to add logic if the game is over.
Open the game manager script and create a private bool variable.
Create a method that if called the bool variable will be switched to true.
To be able to access the Scene manager, which we need to load scenes, we need to open the scene manager library.
Under the Update method we need an if statement.
To be able to use the scene we want we need to add the scene to the build settings. The build setting is under file — build setting.
To add the scene simply drag and drop the scene into the field at the top labeled scenes in build.
Now in the UI script you will need to add a handle for the game manager.
Remember to null check
Now we can use this to call the method on the game manager script to turn the bool to true and activate the function to restart the game.
Place this into a method that is only called when the game over and the restart text is visible, and you have successfully set up an input method for reloading a scene from a game over screen.
You could also use this method to load scenes from a main menu. Remember to experiment with your code, and I will see you in the next tutorial.