Unity Button Scene Switch: Complete Guide
Switching scenes in Unity using UI buttons requires the following steps:
- Create a UI button: Right-click in the Hierarchy panel -> UI -> Button to create a new UI button.
- Create a scene change script: Right-click in the Project panel -> Create -> C# Script to create a new C# script named SceneManager.
- Open the SceneManager script and edit it by using a text editor. Add the following code to the script.
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class SceneManager : MonoBehaviour
{
public Button yourButton;
void Start()
{
Button btn = yourButton.GetComponent<Button>();
btn.onClick.AddListener(TaskOnClick);
}
void TaskOnClick()
{
SceneManager.LoadScene("YourSceneName");
}
}
- Attach the SceneManager script to a button: In the Hierarchy panel, drag the SceneManager script onto the button object, then drag the button’s On Click() event onto the yourButton field in the SceneManager script.
- Change “YourSceneName” in the code to the name of the scene you want to switch to.
- To play the game, click on the game’s “Start” button, then click on the UI button to switch to the desired scene.
Please note that the yourButton field in the above code needs to be assigned in order to reference the button created in step 1. You can manually drag and drop the button object onto the yourButton field in the Inspector panel, or dynamically retrieve the button component in the Start() method.