We now take a small break from the collection of new features and game objects to do a little work to the game package as a whole. In particular, we add a Main Menu rather than throwing the player straight into game play on startup. In Unity-speak, this means creating a new “Scene.” While the menu itself is a pretty small effort, the very concept of switching and managing scenes is now on our radar.
You might recall, one of the early things we did was to delete the “Default” game scene and create a new one called “Game.” We kinda glossed over why that effort was useful, but here it is now. One of the things our game will need in the planning stage is the idea of scene management. Like everything else in programming/Unity, names matter, so the scene names are worth at least a wee-bit of thought.
We create our Main Menu scene the same way we created our Game scene way back when. First, save the current scene, then select from the menu File -> New Scene. This automatically opens a new, Untitled scene. Give it a good name and save it. From this point on, you have to pay attention to which scene is currently loaded in the Unity Editor. You can only have one scene at a time. So, to switch from our fancy new Main Menu scene and back to the game, we have to select from the menu, File -> Open Scene. If you have not saved the current scene, you should be prompted to do so. You can still play the game within Unity, regardless of which scene you have open. But you can only work with and modify the scene currently open.
In order to work with the scenes programmatically, you must add the UnityEngine.SceneManagement
namespace to your code.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
With that, the simplest Use Case is loading or reloading a scene when prompted by the player.
void Update()
{
if ( Input.GetKeyDown(KeyCode.R)
&& gameOver) { SceneManager.LoadScene("Game"); }
}
In our main scene, we will create some graphics and a button. The button will call the LoadGame()
method of our Main Menu class.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class MainMenu : MonoBehaviour
{
public void LoadGame()
{ SceneManager.LoadScene("Game"); }
}
Part of the scene management is in the Build Settings found at File -> Build Settings.
Use the “Add Open Scenes” to add the current scene into the list of “Scenes to Build.” You will notice they each have an index number to the right. This allows for a slightly faster, if less readable mechanism for loading scenes. So, in this case, the following lines are functionally, if not performance equivalent.
SceneManager.LoadScene("Game");
SceneManager.LoadScene(1);
Like all things Unity, everything is an object that can be manipulated in the code. That means, we can watch for a player keypress, then switch scenes as needed with a few simple commands.