Let’s begin with a video on this topic:
Introduction
At any time we can load any Unity scene through code, for example being in the main menu scene we can press a button to start and load a second scene with the first level of the game or load a scene where there is a cinematic that starts playing as soon as the scene loads. Another example could be that we have different levels mounted in different scenes and then in the main menu scene we could have a window with a selection menu in which there is a panel with several buttons and make each button load a different scene.
In this article we are going to see a solution to switch to any scene using buttons in Unity, this solution what it does is to load the scenes by their name through a single script.
Download the Unity package with the Script and example scenes
How to change scene in Unity
Identify the scene to be loaded
There are different ways to change scene in Unity but in all of them it will be necessary to be able to reference in some way the scene that you want to load.
One way to reference a scene could be from the integer value that indicates the position of the scene in the Build Settings window, the first scene starts counting from 0 and is the scene that will be opened as soon as the application is opened.
Another way to reference the scene you want to load can be through the name of the file with which the scene is saved. This is the method used in the solution that can be downloaded above.
Instruction to load a scene in Unity
The code instructions that allow you to load a scene in Unity by its ID number and by its name are as follows:
UnityEngine.SceneManagement.SceneManager.LoadScene(idNumber);
and
UnityEngine.SceneManagement.SceneManager.LoadScene(sceneName);
These instructions can be simplified if the Namespace UnityEngine.SceneManagement is implemented in the script header where they are used, by adding the following line of code in the script header:
using UnityEngine.SceneManagement;
Once this is done the instructions can be summarized as:
SceneManager.LoadScene(idNumber);
and
SceneManager.LoadScene(sceneName);