Javatpoint Logo
Javatpoint Logo

Unity UI Button

The button UI element in unity responds to a click from the user and is used to initiate or confirm an action. Some common examples are: Submit, Ok, and Cancel buttons.

To insert a button element, right in the scene hierarchy, and select GameObject -> UI -> Button. If you don't have an existing canvas and an EventSystem, Unity will automatically create one for you, and place the button inside the canvas as well.

Unity UI Button
Unity UI Button

Game tab:

Unity UI Button

When you play the scene, you will notice that the button already has some standard functionality, such as detecting when the mouse is hovering over it and changing color when you pressed that button.

First of all, create a script file, and rename it to ButtonActions.cs

This script specified a simple method that logs how many times we have hit the button.

Now, create an empty GameObject and attach this script file to it. We do this because a button will not do anything on its own; it only calls the specified method in its scripting.

Unity UI Button

Now, select the Button, and go to the Inspector tab and search for OnClick() property.

Unity UI Button

Click on that + icon on the bottom tab, and when you click, a new entry should show up in the list.

Unity UI Button

This entry defines what object the button press acts on, and what function of that object's script is called. Because of the event system used in the button press, you can generate multiple functions simply by adding them to the list.

Drag and drop the empty GameObject, which contains the ButtonGameObject script we created, onto the None (Object) slot.

Navigate the 'No Function' dropdown list, and look for our OnButtonPress method. For that, go to your Script file name (ButtonAction) and select OnButtonPress () method.

Unity UI Button

When you play the game now, you can test the button, the console prints out how many times you have pressed the button.

Unity UI Button
Next TopicUnity UI Slider




Help Others, Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA