Table of Contents

UI Toolkit

You can use Bindables with UI Toolkit to create dynamic UI, handle events, animations, list views, and more.

Tip

This sample is in the Bindables Package at: Samples/Scenes/09_UIToolkit

Getting Started with UI Toolkit

To use Bindables with UI Toolkit, make sure UnityEngine.UIElementsModule is checked in Tools > Bindables > Settings.

Now you can get a hold of your UIDocument in the scene and start attaching bindings:

class MyBindings : MonoBehaviour
{
    public UIDocument Document;
    public Bindable<string> Text;
    public Bindable<Color> Color;
    public Bindable<float> Size = new(200);

    public void Start()
    {
        var root = Document.rootVisualElement;

        var label = root.Q<Label>();
        var textField = root.Q<TextField>();
        var background = root.Q("background");

        // Every VisualElement type has Bind extensions
        label.BindText(Text);

        // Style properties start with BindStyle*
        label.BindStyleColor(_color);
        background.BindStyleWidth(_size);
        background.BindStyleHeight(_size);
    }
}

BindContext for VisualElements

BindContext controls the lifetime of bindings. When you use Bind* extension methods in the previous example, you get the default BindContext for the VisualElement. The default BindContext for VisualElements becomes invalid once the VisualElement is removed from the hierarchy.

class MyBindings : MonoBehaviour
{
    public UIDocument Document;
    public Bindable<string> Text;

    private Label _label;

    public void Start()
    {
        var root = Document.rootVisualElement;
        _label = root.Q<Label>();

        _label.BindText(Text);
    }

    void RemoveLabel()
    {
        // This will automatically unbind the Text from the label.
        _label.RemoveFromHierarchy();
    }
}

Learn more about BindContext on the BindContext page.

BindEvent for VisualElements

The BindEvent extension method provides a convenient way to register for VisualElement events, and automatically unregister when the VisualElement is removed from the hierarchy:

void Start()
{
    var root = Document.rootVisualElement;
    var button = root.Q<Button>();
    button.BindEvent<ClickEvent>(() => Debug.Log("Clicked!"));
}

Two-way Bindings

For built-in fields like TextField and IntegerField, you often want to bind to a Bindable value, but also update that Bindable value when the user inputs to those fields. This is called a two-way binding, and there are some helpful extensions to make this easy to do:

Bindable<string> TextValue = new("initial text");
Bindable<int> IntValue = new(5);

textField.BindValue(TextValue, twoWay: true);
integerField.BindValue(IntValue, twoWay: true);