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

Creating Reusable UI Components with Bindable Properties

Learners will design modular UI components that accept external data sources, enabling consistent rendering of game information across different menu screens.

In this lesson, you will learn how to create flexible UI components that automatically update their display by binding to external data sources.

The Concept of Data Binding

When building complex menus, you often find yourself writing the same code to update a Label or Progress Bar every time your game state changes. Instead of manually pushing data to UI elements, "Bindable Properties" allow you to define a direct link between a UI component and a data variable. When the data changes, the UI updates itself automatically.

In Unity’s UI Toolkit, we achieve this by creating a custom component script that exposes properties which the UI system can "observe."

Creating a Bindable Component

Imagine you have a PlayerHealthBar component. Instead of passing a reference to the UI element and manually calling .text = health.ToString(), you design your component to expose a property that the UI system recognizes.

public class StatDisplay : VisualElement 
{
    private Label _label;
    
    // This property acts as our bridge
    public string DisplayText 
    {
        get => _label.text;
        set => _label.text = value;
    }

    public StatDisplay() 
    {
        _label = new Label();
        Add(_label);
    }
}

By defining this property, you decouple the internal UI structure from the game logic. You can now use this StatDisplay in your Inventory menu, your HUD, or your Character Sheet. If you want to update the text, you simply set the DisplayText property.

To take this a step further, you can combine this with Observable Patterns (lesson 23), where the UI component subscribes to a data source. When the source value changes, it triggers the property setter, ensuring your UI is always in sync with your game state without you having to manually refresh every element across different screens. This creates a "single source of truth" for your game data, making your UI modular, predictable, and incredibly easy to maintain across multiple game scenes.

Key Takeaway: Bindable properties enable a reactive UI architecture where components automatically reflect changes in your game data, eliminating the need for manual synchronization code.