Introduction
In Unity, you can dynamically load any scene at runtime using C# code. A common use case is changing scenes with a button click—for example:
- Starting the Game: From the main menu scene, pressing a button could load the first level or a cinematic scene that plays automatically.
- Level Selection: If your game has multiple levels (each in separate scenes), you could create a level selection menu in the main menu. This menu could include a panel with buttons, where each button loads a different scene when clicked.
To implement this, you’ll need:
- Scene Management Setup (add scenes to Build Settings).
- A UI Button (with an
OnClick()
event). - A C# Script (using
SceneManager.LoadScene()
).
This approach is essential for smooth transitions between menus, levels, and cutscenes in your Unity game.
In this tutorial, you’ll learn how to switch between scenes in Unity using UI buttons—with just one reusable script. Instead of writing separate code for each button, this solution lets you load any scene by simply referencing its name. Perfect for:
- Main menus → Game levels
- Level selection screens
- Cutscene transitions
We’ll use Unity’s SceneManager
and a single C# script to keep everything clean and efficient. Let’s dive in!
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);