In this lesson, you will learn how to trigger game logic directly from UI buttons using C# delegate callback functions.
When building UI in Unity, the "Visual Tree" defines how your UI looks, but it doesn't automatically know how to talk to your game scripts. To bridge this gap, we use callbacks. A callback is essentially a "hook" where you tell a button: "When you are clicked, please run this specific function."
Registering Callbacks
In UI Toolkit, every Button element has a .RegisterCallback<ClickEvent>() method. Instead of just clicking a button and seeing it depress, this command executes a C# method defined in your script.
Here is a simple example of how to link a UI button to a game function:
using UnityEngine;
using UnityEngine.UIElements;
public class GameMenu : MonoBehaviour
{
private void OnEnable()
{
// 1. Get the root element of the UI Document
var root = GetComponent<UIDocument>().rootVisualElement;
// 2. Find the button by its name defined in UI Builder
Button startButton = root.Q<Button>("StartGameButton");
// 3. Register the callback
startButton.RegisterCallback<ClickEvent>(OnStartClicked);
}
// This is our callback function
private void OnStartClicked(ClickEvent evt)
{
Debug.Log("Game Started!");
}
}
Why Use Callbacks?
By using this approach, you maintain a clean separation of concerns. The UI Document handles the layout, while your C# script manages the behavior. You don't need to poll or constantly check if a button is being pressed; instead, the UI sends a "message" to your code exactly when the event occurs. This makes your system event-driven, efficient, and much easier to debug as your project grows.
Remember to always use .UnregisterCallback<ClickEvent>(OnStartClicked) when your component is disabled or destroyed to prevent memory leaks and unexpected behavior!
Key Takeaway: Callback functions allow your game logic to react instantly and efficiently to user interactions by subscribing to specific UI events.