avatarDaniele Quero, PhD

Summary

The provided web content serves as a comprehensive guide to utilizing Unity UI buttons, detailing their creation, customization, interaction, and event handling.

Abstract

The article titled "The Ultimate Guide to Unity UI Buttons" offers an in-depth explanation of Unity UI buttons, beginning with their basic addition to the canvas via the Unity editor. It describes the Button component, which enables any UI element to function as a button, and highlights the key features such as navigation, transitions, interactivity, and the OnClick event. The guide delves into various button states and how to customize their appearance through color tints, sprite swaps, and animations. It also provides instructions on how to handle button events both through the Unity Inspector and programmatically using scripts, delegates, and event listeners. The article aims to assist developers in creating interactive and visually appealing buttons within the Unity game engine.

Opinions

  • The author emphasizes the versatility of Unity UI buttons, noting that any UI element can be turned into a button with the appropriate component.
  • The guide is written with a practical approach, providing step-by-step instructions and visual examples to aid understanding.
  • The author suggests that mastering button transitions and animations can greatly enhance the user experience.
  • The article encourages the use of the OnClick event and scripting to create complex interactions, showcasing Unity's robust event system.
  • By providing additional resources and links to related topics, the author indicates the importance of continuous learning and exploration within the Unity platform.
  • The author promotes their own work and invites readers to support them by joining Medium, demonstrating a personal stake in the content provided.

How to Unity

The Ultimate Guide to Unity UI Buttons

Unity UI Buttons explained

In Unity, buttons are UI elements that can be added to the canvas using the creation menu.

As per many other elements, the key features of a button can be found in the “Buttoncomponent in the Inspector window, meaning that any Unity UI element can become a button by simply attaching this component.

A newly created button also comes with an Image component, to ensure the possibility of having a custom sprite acting as a button or, in other words, having buttons of any possible shape. Also, a child Text or TextMeshPro (TMP) object is created along.

The button's main features are:

  1. Navigation: Allows to specify how to switch between buttons using a gamepad, keyboard, or mouse when more than one is on the canvas.
  2. Transition: Specifies the visual transition that occurs when the button’s state changes, such as when it is selected or pressed. It could be a shift in colour, in the sprite, an animation
  3. Interactable: Determines whether the button can be interacted with. It can be modified via script for programmatical control.
  4. OnClick: Specifies a list of actions performed when the button is clicked. It is possible to assign them via Inspector or via script.

Navigation

If we click on the Visualize button, on the Scene view arrows will appear showing how the navigation is set by default. We can then change the way the user navigates through buttons using some preset.

Transition

The transition section is governed by choice in the drop-down menu

None” will disable any transition during button interaction

Color Tint” allows transition in colour during interaction and offers the following setting:

  1. Target Graphic: Specifies the image used for the button, if any.
  2. Highlighted Color: Specifies the colour the button’s target graphic will change to when it is highlighted.
  3. Pressed Color: Colour when pressed.
  4. Selected Color: Colour when selected.
  5. Disabled Color: Colour when it is disabled.
  6. Color Multiplier: Specifies a multiplier that will be applied to the button’s target graphic’s colour.
  7. Fade Duration: Duration of the transitions.

Sprite Swap” allows changing the button sprite during interaction.

It offers quite the same settings as above, but instead of choosing an RGB-A colour, we can choose a whole new sprite for each interaction type.

Animation” allows to specify animations that will be triggered when interacting with the button.

Again, for each interaction, an Animation trigger can be set.

Event Handling

OnClick is an event. This means that the Unity EventSystem listens and reacts when the button is clicked, i.e. the OnClick event is triggered.

To add an action to the OnClick event via Inspector, we must click on the plus button. We can drag any object onto the placeholder, usually gameobjects carrying a component with public methods or carrying custom C# scripts having public methods.

In this example, I dragged the main camera. When clicking on the Function drop-down, a list of all eligible components/scripts is shown: the ones with public methods.

In this example, I added several actions, which will be performed in this specific order. Each of them is related to a given function, method or property in the chosen component/script. If it is a property or a method requesting ONE or NONE primitive parameter, the inspector shows a prompt to assign a value to that parameter:

  • a checkbox for booleans
  • an input text area for strings or numbers

If no parameters are needed, no input is shown.

Public methods with more than one parameter will not be shown.

When the button is clicked, those methods are called from that specific component/script instance. But a more programmatical way is possible.

Scripting with Buttons

To add an action to the OnClick event, to Unity buttons, via a script:

  1. Attach a script to the GameObject that contains the button.
  2. Get a reference to the Button component on the GameObject, via the GetComponent method or using the SerializedField attribute.
  3. Create a UnityAction delegate, pointing to a method that can be invoked without arguments.
  4. Add a new listener to the Button.onClick event using the AddListener method and passing in the instance of the UnityAction delegate.
private void Start()
{
    button = GetComponent<Button>();
    UnityAction action = () => Debug.Log("Button was clicked");
    button.onClick.AddListener(action);
}

The following is another way, without lambda functions:

private void Start()
{
    button = GetComponent<Button>();
    UnityAction action = CallAnotherMethod;
    button.onClick.AddListener(action);
}

private void CallAnotherMethod()
{
    Debug.Log("Button was clicked, and now calling another method.");
    //or do something else
}

Or spice things up, also passing parameters (in this way, more than one is allowed) with the help of the delegate keyword:

private void Start()
{
    int p1 = 0;
    string p2 = "Yo Mama";
    button = GetComponent<Button>();
    UnityAction action = CallAnotherMethod;
    button.onClick.AddListener(delegate 
                {
                  ParameterMethod(p1, p2);
                }
    );
}
private void ParameterMethod(int p1, string p2)
{
    Debug.Log($"Calling method with params {p1} and {p2}.");    
}

Check the meaning of the $-symbol (string interpolation in C#) here:

More on Unity Buttons:

Hope you find it useful!

If you liked the article, please clap to it and share it! Also, take a look at my games!

Get access to my stories and those of other Medium writers for just $5 a month. With no additional cost to you, I will receive half of your payments as a commission: it’s a great way to support me!

Join my newsletter and receive regular notifications when I post.

Unity
Unity Ui
Csharp Programming
Recommended from ReadMedium