Day 25: Loading Scenes in Unity
Objective: Go from main menu to game.
To load the game from the main menu scene, we will need to create a new scene. We do this by right-clicking in our project area, create, scene. We’ll name it Main_Menu.
Make sure you save your current scene before double-clicking Main menu scene. Once we are in we will change the camera to have the background to be black.
Then we will add the images and credits text.
Now a button to start the game. In the hierarchy, right click, UI, and button.
Under the new button is a text component. There is were we can change the text on the button.
Now to create to create the logic. We need a new C# Script. We’ll call it MainMenu. In the MainMenu script we will delete the start and update functions. We’ll add a public function called StartGame.
Inside that function we need to call the next scene. To do this we need to add the Scenemanagement namespace. We do this by adding “using UnityEngine.SceneManagement;”
Now in the function we can load a scene we want. We can do this by calling an index or name. We will use the build index. To figure out the build index for a scene we need to go to File->Build Settings. We can drag both scenes we have into the top window. Make sure Main Menu is the first to be dragged.
Now we know the build index we want to call is 1. In the script we’ll type out in the function “SceneManager.LoadScene(1);”
It’s time to use the function. We need to add the script to the canvas game object. And on the Button component, there is a OnClick() area, click the +. You’ll get an area where something can be dropped.
This is where we will drop the canvas to grab the main menu’s public function.
You can now hit play and click the button and the game scene should load.