Table of Contents

BindContext

Consider this binding:

class Player
{
    public Bindable<int> Health;
    public TexMeshProUGUI HealthText;

    void Start()
    {
        HealthText.BindText(Health, health => $"Health: {health}");
    }
}

This code is registering for the OnChange callback from the Health bindable in order to update the HealthText value.

But, how long does this binding last?

The lifetime of bindings is tracked by a BindContext. In this case, the default BindContext for HealthText is used, which will keep the binding active until the HealthText component is destroyed.

To get the default BindContext for a Unity Object or Visual Element, use BindContext.Get:

void Start()
{
    // This is the same as the previous example:
    var context = BindContext.Get(HealthText);
    context.Bind(Health, health => HealthText.text = $"Health: {health}");
}

Manual BindContext

If you want to control the lifetime of your binding more precisely, you can create your own BindContext. Suppose we want a binding that only applies when this component is enabled:

private BindContext _context;

void OnEnable()
{
    _context = new();
    _context.Bind(Health, health => HealthText.text = $"Health: {health}");
}

void OnDisable()
{
    _context.Unbind();
}

BindContext from CancellationToken

You can also create a BindContext from a CancellationToken:

private CancellationTokenSource _cts;

void OnEnable()
{
    _cts = new();
    var context = new(_cts.Token);
    context.Bind(Health, health => HealthText.text = $"Health: {health}");
}

void OnDisable()
{
    _cts.Cancel();
    _cts.Dispose();
    _cts = null;
}

Here are the rules you should keep in mind follow:

  • You can get the default BindContext for Unity Object or Visual Element using BindContext.Get. This is what all built-in extension methods use.
  • The default BindContext of a UnityEngine.Object remains bound until Destroy or DestroyImmediate is called on the object.
  • The default BindContext of a UnityEngine.UIElements.VisualElement remains bound until the element is removed from the hierarchy.
  • If you create your own BindContext with no object or cancellation token, you must call Unbind to clean up event handlers.
  • Use BindContext.AddUnbindAction to add a callback to be invoked when the BindContext is unbound.