Bindable
Welcome to Bindables! This guide will teach you how to add reactivity to your Unity programming.
What is a Bindable?
A Bindable is a container that holds a value and notifies observers whenever that value changes.
using Bindables;
public class Player : MonoBehaviour
{
public Bindable<int> Health = new(100);
}
You can edit a Bindable by assigning to its Value.
Debug.Log($"Current health: {Health}");
Health.Value = 75;
Debug.Log($"New health: {health.Value}");
Change Events
You can use the OnChange or OnChangeWithValue events to subscribe for changes. However, as you'll see in the next section, you'll usually use Binding Extensions instead, which are much more convenient.
void Start()
{
Health.OnChangedWithValue += OnHealthChanged;
}
void OnHealthChanged(int value)
{
Debug.Log($"New health: {value}");
}
void OnDestroy()
{
Health.OnChangedWithValue -= OnHealthChanged;
}
Bindables can be viewed and edited like normal properties in the editor. Change it in play mode to see your debug message get printed.
IBindable
When you want to expose a Bindable as read-only, use the IBindable interface:
class Player : MonoBehaviour
{
[SerializeField]
private Bindable<int> _health;
public IBindable<int> ReadOnlyHealth => _health; // IBindable: read-only
public Bindable<int> ReadWriteHealth => _health; // Bindable: read and write
}
NotifyChanged
If your Bindable type is a class, you can notify observers when internal fields change using NotifyChanged:
class Data
{
public int Health;
}
class Player : MonoBehaviour
{
public Bindable<Data> Data;
void SetHealth(int health)
{
// Does NOT trigger OnChange event because Data.Value hasn't changed
Data.Value.Health = health;
// Manually notify something changed
Data.NotifyChanged();
}
}