Table of Contents

Unity UI (UGUI)

You can use Bindables with Unity UI (UGUI) to create dynamic UI, handle events, animations, list views, and more.

Tip

This sample is in the Bindables Package at: Samples/Scenes/03_TwoWayBind

Getting Started with Unity UI (UGUI)

To use Bindables with Unity UI, make sure Unity.TextMeshPro and Unity.UI is checked in Tools > Bindables > Settings.

Now you can bind to common properties like text and color easily:

class MyBindings : MonoBehaviour
{
    public TextMeshProUUI Text;
    public Image Image;

    public Bindable<string> TextValue;
    public Bindable<Color> ColorValue;

    public void Start()
    {
        Text.BindText(TextValue);
        Image.BindColor(ColorValue);
    }
}

These bindings remain active as long as Text and Image are not destroyed. Learn more about BindContext on the BindContext page.

BindEvent

The BindEvent extension method provides a convenient way to add listeners to UnityEvents and automatically remove them when this is destoyed.

public Button Button;

void Start()
{
    this.BindEvent(Button.onClick, () => Debug.Log("Clicked!"));
}

Event Trigger

EventTrigger is used to register for common events like pointer events. Bindables adds extensions for each of the event types. Here we create a Hoverable component which exposes a Hovering bindable state, and use EventTrigger to listen for those state changes.

[RequiresComponent(EventTrigger)]
public class Hoverable : MonoBehaviour
{
    private Bindable<bool> _hovering = new();
    public IBindable<bool> Hovering => _hovering;

    void Start()
    {
        var evtTrigger = GetComponent<EventTrigger>();
        evtTrigger.BindPointerEnter(_ => _hovering.Value = true);
        evtTrigger.BindPointerExit(_ => _hovering.Value = false);
    }
}

Two-way Bindings

For built-in input components like InputField and Slider, 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<float> FloatValue = new(5.0f);

inputField.BindText(TextValue, twoWay: true);
slider.BindValue(FloatValue, twoWay: true);