When making the user interface for your game, you need to make the buttons do things when they are clicked. In this article, you will learn how to change the scene when a button is clicked.
Making a Button Change the Scene
Adding the Button
Let’s learn how to change the scene with a click of a button in Unity.
First, you need to add your scenes to the Scenes In Build list. To do this, go to File > Build Settings.
Click the Add Open Scenes button.
Switch to the second scene and click the button again.
Switch back to the first scene. Add a button by right clicking the Hierarchy panel and choosing UI > Button.
If you get a message asking you to import the TMP Essentials, click the Import TMP Essentials button.
Coding the Button Functionality
Next, create a new script by right clicking the Project panel and choosing Create > C# Script.
Name the script UIController, for example, and open the script.
In order to make something happen when the button is clicked, you need to create a function. Declare a public function named ChangeScene, for example. To load a scene, you need to import the SceneManagement namespace.
Now, inside the ChangeScene function, call for the LoadScene function that is in the SceneManager class. Inside the parentheses of the function you need to add the index of the scene you want to load. The index can be seen in the Scenes In Build list of the Build Settings window. In this particular case the index of the second scene is 1.
Save the script with CTRL + S and go back to the editor.
To use the script in the game, it needs to be added to an object as a component. Select the Canvas object, for example. Drag the script from the Project panel to the Inspector panel.
Now, select the button and add a new item to its OnClick list by clicking the plus icon. Drag the Canvas object from the Hierarchy panel to the empty field in the OnClick list.
Open the dropdown menu, choose your UIController script and the ChangeScene function you created.
There you go. You can now start the game and click the button to change the scene.