top of page

004-Adding Buttons

1.1 Introduction

In this tutorial we are going to learn about Unity Editor's button functionality with which we can make custom functions run by clicking the button.

Along with this we will cover the selection functionality in editor that allows us to get the currently selected gameObjects in the editor

1.2 Basic Setup

1. Open the folder 004 and open the FifthEditorWindow.cs script.

2. Make the current script inherit from EditorWindow

3. Setup a basic editor window as taught in the previous tutorials with menu address as :"MyEditors/MyFifthEditorWindow"

image.png
1.2 Adding GUI Function

1. Add OnGUI() function to the script. OnGUI() function helps us to draw inside of the editor window whatever we want to draw.

2. In the OnGUI() function we can draw anything ranging from simple integer fields to buttons and more.

image.png
1.4 Adding our first button

1. To add our first button we are going to be using GUILayout which contains Button function.

2. To draw a simple button We use GUILayout.Button("Name of the function")

3. Below we have added three buttons namely: "First Button","Second Button" and "Third Button". These are now visible in the editor window.

image.png
image.png

But clicking on these buttons doesn't perform anything

1.5 Registering button click

1. Whenever the button is clicked it returns a true value which means we can link a logic to the button using the if statement.

2. Let us add a logic to each of the button click within the if statement

image.png
image.png

Now pressing each of the button we are able to debug their respective texts.

​

1.6 Selection functions

1. Selection class holds properties that are useful in determining which transforms or gameObjects are currently selected

2. Selection.activeTransform-currently selected transform

3. Selection.gameObjects-Returns array of currently selected gameObjects.

image.png

In the above example we have four selected gameObjects namely A,B,C and D

1.7 Making Buttons to print names of currently selected transform

Let us write a function that prints the currently selected Transform

image.png

Let us make a button in the editor that prints the currently selected transform

image.png

After connecting the function to the button we are able to print the name of the currently selected transform.

image.png
1.8 Printing names of multiple selected transforms

1. Similar to previous let us add a button called as "Print multiple selected transform names"

2. Now add a function called MultiplSelectionNames() that prints the name of currently selected multiple transforms.

image.png
image.png
image.png

This is now able to print the names of currently selected as well as multiple selected objects.

End

Kindly support me through my Patreon account if you find these tutorials useful. Feel free to connect with me on Twitter. This support enables me to create more educational content.

bottom of page