Loading Scenes in Unity
Aight, quick article here about loading Scenes in Unity! In our example game we have two Scenes: MainMenu, and Game. First things first, we gotta add these scenes to the Build.
We’re gonna open up the Build Settings by going to File → Build Settings… You can also use the shortcut Ctrl + Shift + B to open the Build Settings window. Here, we can add our open scenes to the Build:
In the MainMenu Scene, I’ve added a UI Button (New Game) hooked up to the MainMenu script’s method, LoadGame(), to Load the Game Scene:
And in the MainMenu script in the LoadGame() method, we have one line of code, on Line 22, that loads our Game Scene: SceneManager.LoadScene(int sceneBuildIndex):
The parameter for SceneManager.LoadScene() can either be a string of the name of the Scene, or the index of the Scene in the Build Settings. Using an Index is a bit more performant than using strings, so we’re gonna use the Index. But I’m not more machine now than man, so I add a comment letting and other folks reading this code know that Scene Index 1 is the “Game Scene”.
And as always, we test out our code: