Unity – The Button
In this chapter, we will earn how to insert UI elements into our scene and go about working with them.
Let us start off with a Button. To insert a button, right click in the Scene Hierarchy and go to Create → UI → Button. If you do not have an existing Canvas and an EventSystem, Unity will automatically create one for you, and place the button inside the Canvas as well.
Remember that in Overlay rendering mode, which is the default mode, the size of the Canvas is independent of the size of the camera. You can test this by clicking on the Game tab.
If you play the scene, you will notice the button already has some standard functionality such as detecting when the mouse is hovering over it, and changing color when pressed.
A Button requires functionality to be actually useful in the UI. This functionality can be added through its properties.
Let us create a new script, and call it ButtonBehaviour.
public class ButtonBehaviour : MonoBehaviour { int n; public void OnButtonPress(){ n++; Debug.Log("Button clicked " + n + " times."); } }
We have made a simple method that logs how many times we have hit the button.
Note − This method has to be public; it will not be noticed by the Button’s functionality otherwise.
Let us create an empty GameObject and attach this script to it. We do this because a button will not do anything on its own; it only calls the specified method in its scripting.
Now, go into the Button’s properties, and find the OnClick() property.
Hit the + icon on the bottom tab, and a new entry should show up in the list.
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 trigger multiple functions simply by adding them to the list.
Drag and drop the empty GameObject, which contains the ButtonManager script we created, onto the None (Object) slot.
Navigate the No Function dropdown list, and look for our OnButtonPress method. (Remember that it can be named anything you want, OnButtonPress is simply a standardized naming convention.) You should find it in the ButtonBehaviour section.
If you play the game now, you can test the button and surely enough, the console prints out how many times you have pressed the button.