Loading Scenes in Unity
Objective: Reload the scene after the player dies using R key
Continuing on from the last post, we added another text ui element to show the users they could press the R key to restart the level. We did this following the same steps as the game over text in the last post, bar the flickering.
Next we create an empty game object and rename it Game_Manager, then create a C# script called GameManager and attach it. Open the script and we need a bool to identify if the game is over so that we can make sure that pressing the R key during game play doesn’t reload the scene when getting that new high score. Create a serialized private bool called isGameOver. Next create a public void GameOver method that sets the isGameOver bool to true.
Inside the Update method run an if statement to check if the R key was pressed AND isGameOver is set to true. We need to use the SceneManager so import the UnityEngine.SceneManagement namespace.
Inside the Update methods if statement, using the SceneManager, load the scene by name (Game in this case) or int value. To run this you need to add the scene in the build settings so, go to File, Build Settings and add the open scene.
Now you can see in the build settings that the scene has a value of 0. This could be used to load the scene instead of the name. Using the int value is a quicker and more efficient way of loading the scene.
We need to call the GameOver method to set isGameOver to true. Inside the UIManager script, set a global reference varaiable of private GameManager called gameManager and assign it in the Start method using a GameObject.find and GetComponent. Finally after starting the GameOver coroutine call the Game Managers GameOver method to activate the logic which allows the user to press the R key to restart the level.
In the next post, we will move onto adding in some game effects (VFX).