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
BindContextfor Unity Object or Visual Element usingBindContext.Get. This is what all built-in extension methods use. - The default
BindContextof aUnityEngine.Objectremains bound untilDestroyorDestroyImmediateis called on the object. - The default
BindContextof aUnityEngine.UIElements.VisualElementremains bound until the element is removed from the hierarchy. - If you create your own
BindContextwith no object or cancellation token, you must callUnbindto clean up event handlers. - Use
BindContext.AddUnbindActionto add a callback to be invoked when theBindContextis unbound.