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
EasyMake each portal load the scene its sceneName names.
- At the top of
Portal.cs, addusing UnityEngine.SceneManagement;. - Write
void OnTriggerEnter(Collider other): whenother.CompareTag("Player"), callSceneManager.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
2Buttons and Screens
Buttons and onClickLambdasWiring in the InspectorPanels On and OffHealth BarsRecap: Upgrade Shop5Saving with PlayerPrefs
Save a NumberLoad with a DefaultHigh ScoreSave SettingsRecap: Coins in the Bank3The Game Manager
One Script Runs the GameThe SingletonGame StatesSwitching on the StateRecap: Round Manager6Project: Endless Runner
Three LanesObstacles Ahead9The New Input System
Two Input SystemsKeyboard and MousePressed This FrameInput ActionsRecap: Input SwapPractice on your own: Unity playground