Loading Scenes in Unity
Game Over! How Do I Reload the Scene?
In order to restart my game after all my lives are gone, I need to reload the Scene to start over.
- I started by going into my “UIManager” script and creating another Text variable named “_restartText” and added the [SerializeField] attribute to allow access in the Inspector.
- I then dragged the “Restart_Text” object from the Hierarchy panel into the “Restart Text” slot.
- To make it easier to find the game over logic and avoid too much clutter, I separated the game over logic into its own method inside the “UIManager” script and named it “GameOverSequence()”. When current lives equal 0, I call on the newly created method, “GameOverSequence()”.
- Next, I created an empty object and named it “GameManager”.
- I then created a C# script with the same name and attached it to the “GameManager” game object I just created.
Loading a Scene
The next step is to enter the logic for when a player presses the ‘R’ key.
Note: In order to manage scenes in Unity, you must include the SceneManagement namespace library.
- Inside the “GameManager” script, I added the following code.
Note: I named my current scene, "Game". In order to load the scene, I used the name of the scene in the following line: SceneManager.LoadScene("Game");For quicker loading, as Strings are a little slower, you could use the scene number. In this case it would have been written as follows:SceneManager.LoadScene(0);
- I had to add a handle to the GameManager in the “UIManager” script and check that the GameManager isn’t null.
- I added the code to “Find” the GameManager component.
- I then I added the call to the “GameOver()” method in the “GameOverSequence()” method.
- In order to get the scene to load when pressing the ‘R’ key, I need to add the scene to the build settings.
Checking if Scene Loads
Finally, I play the game and lose my 3 lives to see if pressing the ‘R’ key activates “LoadScene”. Just as I expected…..Game restarts as intended.