Load scenes in Unity

Samarth Dhroov
3 min readMay 20, 2021

--

This place is probably the beginning of a larger context of Gameplay.

The task at hand is to jump between scenes as per the status of the game. Specifically, in the example here, if the player is dead, the need is to restart the scene.

Which tool is useful to accomplish this task? Game Manager.

But before jumping the guns, here are a few configs that must be in place.

Since the interactions are going to happen between UI and the Game Manager, the UI shall have a reference in place for the trigger point.

In the example here, a text element would behave as a trigger point to initiate a scene.

  • Get a text element on the canvas and place it as per your choice.
Unity
  • Create an empty object named “Game Manager” and a script named “GameManager”. Also, attach the script to the object.
Unity
  • Declare a serialized field to connect the text element to the UI Manager.
C#
Unity
  • Disable the Restart text element in the inspector. (The code will do it :) )
_restartText.gameObject.SetActive(false); // In start( ) method.
....
_restartText.gameObject.SetActive(true); // In GameOver( ) method.
  • Open the UI Manager script and add a handle to communicate with the Game Manager.
private GameManager _gameManager;
.....
_gameManager = GameObject.Find("GameManager").GetComponent<GameManager>();
  • Include UnityEngine’s “Scene Management” namespace in the Game Manager script.
  • Go to Unity’s build settings and add the current scene where you’d be able to see the scene number.
Unity
  • The following code shall do the remaining job.
{
private bool _isGameOver = false;

void Update()
{
if (Input.GetKeyDown(KeyCode.R) && _isGameOver == true)
{
SceneManager.LoadScene(0);
}
}

public void gameOver()
{
_isGameOver = true;
}
}
  • Call the gameOver( ) method from the UI Manager using the handle created earlier.
_gameManager.gameOver();
  • Below is the result.
Unity

To extend this a little further by adding another scene, we can understand it in totality.

I am taking this premade scene for granted here. But it could be any scene within your game. Also, the trigger here is a button on UI that by default gets an OnClick( ) method.

Unity

The canvas holds the button element as well as a mainMenu script which initiates a shift between scenes upon a click on this button.

  • Add the new scene in the build settings and arrange as per choice.
Unity
C#
Unity

The final result is here :)

Unity

Thank you very much

--

--

No responses yet