Loading scenes in Unity

Goal today is adding a prompt to press the R key to restart my game, as well as looking into how to load scenes in Unity so I can revert the game back to the start state when R is pressed.

To start, I create a new text object that says ‘Press R to restart the game’ then I’m gonna position it, and make it inactive. In order to make it only display when the game is over, I’m going to stick it with the GameOverFlicker() code during the GameOverUI() call.

You can see me call on the GameManager I’m about to create at the top.

But I don’t want to deal with restarting the scene or determining if I’m dead in the UI Script, because that’s a little out of place. So I’m going to make a Game Manager to handle scenes by creating another empty GameObject and a new script named GameManager.

Then I’m going to create a boolean for _isGameOver and manage it with a public GameOver() call.

Lastly, I’m going to run a void Update() to determine if the game is over, and if I press the R key to restart. But how do I restart?

I’m going to place ‘Using UnityEngine.SceneManagement’ up at the very top, so that I’m able to call on the SceneManager, giving me the ability to use

SceneManager.LoadScene(SceneManager.GetActiveScene().name);

in a If statement checking for _isGameOver and Input.GetKeyDown, this will call the name of the current scene, and load that scene, effectively reloading the game. THOUGH, I could also go to the build settings and determine the scene number there, in order to call it directly.

You can see here, my ‘Game’ scene is scene 0, so I would have used SceneManager.LoadScene(0);.

Now when the Player dies, I can press ‘R’ on my keyboard to load the scene over and it restarts from the beginning.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store