Introduction
This article demonstrates how to make Unity change the scene on a button click using C# scripts.
Prerequisites
Unity Environment version 2018.4.19f1
Create a New Project
Create panel in Unity
First, you have to open the Unity project. Create the Panel for your game.
The panel will add text on the Scene view
Click on the "GameObject" menu in the menu bar. Select UI and pick the "Text" option.
The canvas will be added to the button.
Import the Button icon.
Drag n Drop Exit button icon on the Scene view.
Drag n Drop a Previous and Next button icon on the Scene view.
Select the Scene1 on Click (Ctrl + D). Create a Duplicate Scene2.
Create the Scripts
Right-click on Assets. Select Create >> C# script
Rename the Scripts as Exit.
Double click on the Exit script. Write the code as shown below:
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class Exit: MonoBehaviour {
- public void exitgame() {
- Debug.Log("exitgame");
- Application.Quit();
- }
- }
Save the Program
Drag and drop the Exit script onto the Exit button change Scene on a Button click.
Create the Scripts
Right-click on Assets. Select Create >> C# script
Rename the Scripts as SceneChange.
Double click on the Scenechange script. Write the code as shown below:
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- using UnityEngine.SceneManagement;
- public class SceneChanger: MonoBehaviour {
- public void Scene1() {
- SceneManager.LoadScene("Scene1");
- }
- public void Scene2() {
- SceneManager.LoadScene("Scene2");
- }
- public void Scene3() {
- SceneManager.LoadScene("Scene3");
- }
- }
Save the Program
Create an Empty Gameobject.
Select the Game Object >> Create Empty GameObject.
Rename the empty gameobject as a Scene change.
Drag and drop the Scenechange script onto the change Scene on Button click.
Click on the "File" menu in the menu bar. Select the build settings, switch the platform, and add an Open scene select.
Click on the Play button. Select change Scene on Button click.
For runtime, select the Button as the Scene1 Change On Click in Unity.
For runtime, select the Button as the Scene2 Change On Click in Unity.
For runtime, select the Button as the Scene3 Change On Click in Unity.
Summary
I hope you understood how to make Unity change the scene on a button click using C# scripts.