Unity allows to create multiple scenes but how do you switch between them with a script? In this tutorial you will learn how to create two scenes and switch between them by clicking a button.
Using a Unity button to switch between scenes.
Create two scenes
Create a new Unity3D project
Save the current scene (CTRL-S) as main
Create a new scene in the Project view and name it menu
Create a C# script and name it SceneSwitcher
Your Project window should look like this:
Change script to open scenes
Doubleclick SceneSwitcher to open in Visual Studio
Create public methods GotoMainScene and GotoMenuScene
Your code should look like this:
using UnityEngine;
using UnityEngine.SceneManagement;
public class SceneSwitcher : MonoBehaviour
{
public void GotoMainScene()
{
SceneManager.LoadScene("main");
}
public void GotoMenuScene()
{
SceneManager.LoadScene("menu");
}
}
Create buttons to trigger the script
Open scene menu by doubleclicking it
In the hierarchy window click Create > UI > Button
Expand Canvas > Button > Text
Change text to Start game
In the hierarchy window, choose Create > Create Empty
Rename the new emtpty GameObject to GameController
Drag the SceneSwitcher script to GameController
Select the button and find the On Click event in the inspector
Select Edit and Runtime
Click the little circle next to None (Object) and select GameController
Select SceneSwitcher > GotoMainScene
Repeat creating a button to go to menu scene
Open scene main by doubleclicking it
In the hierarchy window click Create > UI > Button
Expand Canvas > Button > Text
Change text to Menu
In the hierarchy window, choose Create > Create Empty
Rename the new emtpty GameObject to GameController
Drag the SceneSwitcher script to GameController
Select the button and find the On Click event in the inspector
Select Edit and Runtime
Click the little circle next to None (Object) and select GameController
Select SceneSwitcher > GotoMenuScene
Written by Loek van den Ouweland on 2017-10-12.
Questions regarding this artice? You can send them to the address below.