Unity: Loading Game Scenes
Games created in Unity usually contain more than just a single game scene. Take a Main Menu for example. This most likely was stored in another scene. When you press the “Play” button, the game tells Unity to load another scene.
Another example could be different levels of, let’s say a Platformer game. Level 1 is a different scene, level 2 is stored in another scene, and so on…
As the Space Shooter has a Main Menu as well, let’s implement some logic to load into the game scene, as soon as the Player presses the “Play!” button.
Setting up the GameManager.cs script
First of all, we need to include the Unity specific library for managing scenes.
It is simply called UnityEngine.SceneManagement;
Add it to the very top of the GameManager.cs script:
The rest is done rather quickly.
Creating the “Play” button logic
We want to load the Game scene as we press the Play button. For this, we simply need to tell Unity to load another scene. We do so, by using the following line of code:
As you can see from the tooltip, we now have two ways to input the scene we want to load. We can either use the sceneIndexBuild (which is an int number) or we use the sceneName (which is of type string).
We go with option 1 here, so we are using the scene index number.
How to find the scene index number
In order to get the scene number you need, you just need to open up the Unity Editor > File > Build Settings…
At the top of the window, you can see “Scenes in Build”. Here are both scenes listed that we have created. At the very right, there is a number. This is the scene index we need.
- The MainMenu scene has index 0
- The Game scene has index 1
As we want to load the Game scene, we need to input the 1 inside the script:
Why is the method public and not private?
We just created a public method because we need to give the Play button some logic. In order to do so, we need a GameManager GameObject which has to be able to see the method. A private method can just be accessed and seen inside the same script. Another GameObject has to access the method. Therefore, we need a public method here.
Assign the logic onto the buttons
To assign the logic, we need to create another GameObject which is holding the script with the StartGame() method.
- Create a new GameManager GameObject
- Add the GameManager.cs script
- Click on the StartGame_button
- Scroll down and look for Button > On Click()
- Drag the GameManager GameObject inside the (None) box
- Click on No Function > GameManager > StartGame()
To test this out inside the Editor, change Runtime Only to Editor and Runtime.
Here is the finished end result which will change the scene on demand: