In this simple tutorial, we will create a script that will allow you to attach it to any buttons to change to any scene.
Create a script called ChangeScene.
- To create a new C# Script, right click in the Project Panel
- [Create > C# Script]
Create an empty GameObject called SceneManager.
- To create an empty GameObject, right click in the Hierarchy
- [Create > Create Empty].
- Rename the empty GameObject to “SceneManager“.
- It is in best practice to reset the transform of the empty GameObject to the world origin.
Attach the ChangeScene script to the SceneManager.
- There are two ways to approach this:
- 1. Click on SceneManager that you created and in the Inspector click on Add Component. In the search bar search for ChangeScene and click on it.
- 2. Click on SceneManager that you created, and from the Project Panel, drag and drop the ChangeScene script to the SceneManager‘s Inspector.
Edit the ChangeScene Script
- Open the ChangeScene script by double clicking the ChangeScene script in your Project Panel.
- Your Integrated Developement Environment (IDE) will load up.
- Eg. Visual Studio, VS Code, MonoDevelop, etc.
- Once your IDE has loaded it will look as below.
Add the following script. Make sure to include
using UnityEngine.SceneManagement as a part of your library on top.
Or you can copy the script below.
public class ChangeScene : MonoBehaviour
public string SceneName;
public void ChangeToScene()
- Save the script.
Go back to Unity and your SceneManager should be updated as below.
To test out the change scene script we have to add another scene aswell as a UI Button.
- To create a new Scene, right click in the Project Panel, [Create > Scene]
- Name the Scene as NextScene.
- To create a UI Button, right click in the Hierarchy [UI > Button].
- Set the transform of the button as follow.
- You can also change the Text in the Button to “Next Scene” for example, make sure to size and align it accordingly.
Add the functions for the button.
- To add the functions for the button, scroll down the button and find the OnClick() function, click on the [+] icon and drag the SceneManager in the empty area.
- Click on the No Function and find [ChangeScene > ChangeToScene()]
Now you have setup the button’s function.
Assigning which scene to change to.
- In your SceneManager, type in NextScene scene in the ChangeScene script’s properties.
- NOTE: The text in your ChangeScene properties can be changed accordingly to which scene you want to change to depending on the scene.
- Make sure to add the scenes that you want to change to in your Build Settings.
- Go to [File > Build Settings] on the top left.
- You can drag and drop the scenes that you want to change to from the Project Panel to the Build Settings’s Scenes in Build.
- Run the scene and click on the button. You are now set to go.