How to Load a Scene or Exit the Game in Unity

Published

If you are making a game, chances are there are several levels in it, with their own layout and logic so you’ll be organizing your game in different scenes. But how do you navigate between scenes? How do you load a scene at runtime in Unity? Also, how can you exit your game?

Well, it’s really simple just follow the steps to become a Pro at Scene Management in Unity.

Include your Scenes in your Build Settings

In order to navigate between scenes, they need to be added to your Build Settings even when you are play testing in the Editor. Go to File > Build Settings to access these settings.

Build Settings Screen
Your Project's Build Settings Window

Now that the Build Settings window is open, you can add scenes. You can add the currently opened scenes by clicking the “Add Open Scenes” button or, more useful, you can drag and drop scenes from the explorer to the Build Settings window.

Scene Management in Unity is handled by the aptly named SceneManagement module. To access it, you simply need to add “using UnityEngine.SceneManagement;” to your script.

This allows you to call the SceneManager.LoadScene function which has 2 overloads:

  • Either pass an integer value, which represents the id of the scene as shown in the Build Settings Window
  • Or you can use the name of the Scene as a string.

Quitting is also very straightforward: you only need to call Application.Quit()

Procedurally Generated Levels: Reload the Scene!

If you are using procedurally generated content in your game, where a script instantiates everything when the scene is loaded, you are in luck!

The nice trick is simple: you can reload a currently open scene through the SceneManager. This should clean up the scene and load it anew, as if you were navigating to it for the first time.

Sample Code

using UnityEngine.SceneManagement;

public class StateManager : MonoBehaviour
{

    public void GoToScene(int idScene) {
        SceneManager.LoadScene(idScene);
    }

    public void GoToScene(string nameScene) {
        SceneManager.LoadScene(nameScene);
    }

    public void GoToMainMenu() {
        SceneManager.LoadScene("MainMenuScene");
    }

    public void ExitGame() {
        Application.Quit()
    }
}