Loading Scenes in Unity

  • 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.
Adding Text Variable ‘_restartText’
Dragging Restart_Text into Corresponding 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.
Adding Code to GameManager Script
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.
Adding Code to UIManager Script
Calling GameOver()
  • In order to get the scene to load when pressing the ‘R’ key, I need to add the scene to the build settings.
Adding Scene to 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.

Testing LoadScene

Thank you for taking the time to ready my article. If you would like to stay updated on this project, please follow me here on Medium.

--

--

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
James Hills

James Hills

I am a married father of 5 children. I decided at 13 years of age that I was going to become a Software Developer.