Menu
CoddyTech

Load a Scene

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

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

A hub with two portals. This build has three scenes: Hub (the first), Desert and Glacier. In the Hub, one portal leads to the Desert and one to the Glacier, and each of those has a portal back to the Hub. Every portal has the Portal script, and the Inspector sets its sceneName to where it leads. The arrows walk the Player (ready).

Write Portal.cs: when the Player (tagged Player) walks into a portal, load the scene named in that portal's sceneName.

Press Play, visit both places, then Check.

Try it yourself

using UnityEngine;

public class Portal : MonoBehaviour
{
    public string sceneName;

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

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Building Real Games