Restarting A Scene In Unity3D
Objective: Reload the current scene when pressing the ‘R’ key after the Player GameObject is destroyed.
Step 1: Click the File dropdown menu and select Build Settings…. Then click the Add Open Scenes button to add the current Game scene. Notice that the Game scene was assigned a value of 0. Close the Build Settings window.
Step 2: Create a new Empty GameObject by right-clicking in the Hierarchy window and name it Game_Manager. Then create a new C# Script call GameManager and attach it to the Game_Manager GameObject in the Hierarchy window.
Step 3: In the GameManager script, add the UnityEngine.SceneManagement library to the namespace section to access the SceneManager.
Step 4: Create a private bool called _isGameOver and have it set to false.
Step 5: Create a public method called GameOver() and set _isGameOver to true.
Step 6: Create a public method called RestartLevel(). Within this method, create an if statement saying that if the ‘R’ key is pressed and _isGameOver is equal to true, load the Game scene, also known as scene 0.
Step 7: Call the Restart() method within the Update() method.
Step 8: In the UIManager script, to set _isGameOver to true, create a private variable of type GameManager called _gameManager, access the GameManager script component in the Start() method and assign it to the _gameManager variable, and null check _gameManager.
Step 9: In the GameOverSequence() method, call the GameOver() method from the GameManager script.