English 中文(简体)
Unity - The Button
  • 时间:2024-09-17

Unity - The Button


Previous Page Next Page  

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 cpck 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.

Create UI Button

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 cpcking on the Game tab.

Overlay Rendering Mode

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

A Button requires functionapty to be actually useful in the UI. This functionapty can be added through its properties.

Let us create a new script, and call it ButtonBehaviour.

pubpc class ButtonBehaviour : MonoBehaviour {
   int n;
   pubpc void OnButtonPress(){
      n++;
      Debug.Log("Button cpcked " + n + " times.");
   }
}

We have made a simple method that logs how many times we have hit the button.

Note − This method has to be pubpc; it will not be noticed by the Button’s functionapty 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.

empty GameObject

Now, go into the Button’s properties, and find the OnCpck() property.

OnCpck() Property

Hit the + icon on the bottom tab, and a new entry should show up in the pst.

New Entry

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 pst.

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

None Object slot

Navigate the No Function dropdown pst, 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.

Advertisements