Introduction
This article demonstrates how to create a feature to open a panel in unity by clicking a button using C# scripts.
Prerequisites
Unity Environment version 2018.3.0f2
Create a New Project
Create Button in Unity
First, add a UI button if there is no canvas. It is created automatically. Then, click on the "GameObject" menu in the menu bar. Select UI and pick the "Button" option.
The text of the button is set Transform in Unity
The canvas will add a Panel on the Scene view.
Click on the "GameObject" menu in the menu bar. Select UI and pick the "panel" option.
Open the Panel and after that, add a panel, resize it, and set the color to a black tone.
The Panel will be added to the text.
Add text to this panel in a Click on the "GameObject" menu in the menu bar. Select UI and pick the "Text" option.
The text UI part was very fast Edit the panel text in the scene view.
Set the Background image in the scene view
Open this panel dynamically so deactivate
The request was about how to open this panel dynamically so deactivate the panel by default in the inspector so that it is not visible.
Create the folder
Create a c-sharp script. To open it means to activate it. So first I create a new folder. Right-click on Assets. Select Create >> folder
Rename the folder as Scripts
Create the Scripts
Add scripts and inside of this folder, I add a new C-sharp Script, Right-click on Assets. Select Create >> C# script.
Rename this script, for example, Openpanel.
I double click it and it will open Visual Studio 2019, which is my programming integrated development environment (IDE) for Unity. Write the code as shown below:
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class OpenPanel: MonoBehaviour {
- public GameObject Panel;
- public void PanelOpener() {
- if (Panel != null) {
- bool isActive = Panel.activeSelf;
- Panel.SetActive(!isActive);
- }
- }
- }
Save the Program
Drag and drop the OpenPanel script onto the button Open Panel on a Button click.
To make the OpenPanel script a component to the button, I just drag it into the inspector with the button selected. After that, I assigned the panel to the public panel variable that we added to the script. Now the open panel method should be called on clicking the button. I used the on click event. You can see this here in the inspector, then I drag in the button and select the panel OpenPanel OpenPaneler.
Start this game by clicking on the Play button.
The panel will be opened by clicking on the toggle button.
Summary
I hope you understood how to create an open panel feature on a button click using C# scripts.