Menu
CoddyTech

Load a Scene

Part of the Building Real Games section of Coddy's Unity journey. Lesson 17 of 60.

A Unity game is split into scenes: a menu, each level, the credits. Each scene is a file of its own with its own objects, and a script switches to another one with SceneManager.LoadScene, from the UnityEngine.SceneManagement namespace. This menu's Play button, wired in the Inspector, opens the Forest level:

using UnityEngine;
using UnityEngine.SceneManagement;

public class MainMenu : MonoBehaviour
{
    public void Play()
    {
        SceneManager.LoadScene("Forest");
    }
}

Unity can load only scenes that are in the build's scene list: in Unity 6 that is File > Build Profiles, under Scene List (older versions call the window Build Settings). The name must be the scene file's name, exactly. With a scene missing from the list, or a typo such as "Forrest", nothing loads and the Console shows an error that begins Scene 'Forrest' couldn't be loaded and says the scene has not been added to the build, and the game stays in the menu.

The switch is not instant. The rest of the current frame runs first, so lines after LoadScene still execute; at the start of the next frame Unity destroys every object of the old scene and builds the new one, whose scripts start again with Awake and Start.

challenge icon

Challenge

Easy

Make each portal load the scene its sceneName names.

  1. At the top of Portal.cs, add using UnityEngine.SceneManagement;.
  2. Write void OnTriggerEnter(Collider other): when other.CompareTag("Player"), call SceneManager.LoadScene(sceneName);.

Press Play and walk into each portal: Desert, the Hub and Glacier load in turn. Then Check.

Try it yourself

using UnityEngine;

public class Portal : MonoBehaviour
{
    public string sceneName;

    // when the player walks in, load the scene named sceneName
}

All lessons in Building Real Games

Practice on your own: Unity playground