Course contentsShow
← Unity Game Development
Lesson 311 of 8285. UI and Audio SystemsFree lesson

Handling UI Events and User Input

Register event callbacks to capture clicks, scrolls, and keyboard inputs, enabling seamless interaction between the player and the UI system.

In this lesson, you will learn how to make your UI Toolkit interfaces interactive by registering event callbacks that respond to user clicks, scrolls, and keyboard inputs.

Understanding the Event Propagation

In the UI Toolkit system, events work through a "propagation" flow. When a user interacts with an element—like clicking a button or scrolling through a list—an Event object is generated. This event travels from the root of your visual tree down to the specific element (the "trickle-down" phase) and then back up to the root (the "bubble-up" phase). By registering a callback, you can "catch" this event as it passes through your element.

Registering Callbacks

To make an element interactive, you use the .RegisterCallback<T>() method. The type T defines the specific interaction you are interested in, such as ClickEvent, WheelEvent, or KeyDownEvent.

Here is a simple example showing how to listen for a click on a specific element:

using UnityEngine.UIElements;

public void SetupUI(VisualElement root)
{
    Button myButton = root.Q<Button>("MyButtonId");

    // Register a callback for a click interaction
    myButton.RegisterCallback<ClickEvent>(OnButtonClicked);
}

private void OnButtonClicked(ClickEvent evt)
{
    Debug.Log("The button was clicked!");
    
    // Stop the event from moving further up the hierarchy if necessary
    evt.StopPropagation();
}

Handling Keyboard and Scroll Input

Beyond clicks, you can capture more granular input. For instance, you might want to trigger an action when a user presses a specific key while focused on a panel, or handle custom zoom logic using WheelEvent. Because these events carry data, you can inspect them inside your callback function—for example, checking evt.keyCode within a KeyDownEvent to see which key was pressed.

By decoupling your logic into these specific callbacks, you keep your code clean and ensure that your UI elements respond only when they are meant to, preventing input from "leaking" into the game world when it should only be affecting the interface.

Key Takeaway: Use RegisterCallback<T>() to intercept specific input events at the element level, allowing your UI to react dynamically to user interaction while maintaining control over event propagation.