OnValueChanged Event

1_ScriptableVariable

You can bind callback methods when the variable value changes. Peek at the Health.cs class. As you can see, you can bind yourself to a variable. You don’t need to constantly check in Update() for its value, you can simply subscribe to the OnValueChanged event that is called every time the value changes.

private void Start()
{
    _currentHealth.Value = _maxHealth.Value;
    _currentHealth.OnValueChanged += OnHealthChanged;
}

private void OnDestroy()
{
    _currentHealth.OnValueChanged -= OnHealthChanged;
}

private void OnHealthChanged(float newValue)
{
    var diff = newValue - _currentHealth.PreviousValue;
    if (diff < 0)
    {
        OnDamaged(Mathf.Abs(diff));
    }
    else
    {
        OnHealed(diff);
    }
}

If you are familiar with the UniRx library, it works the same as the reactive property. In SOAP it acts as a reactive property that can also solve dependencies by being a scriptable object.

Note: do not forget to unsubscribe to the event in OnDestroy() or OnDisable(). As the scriptable variable is an asset, the event is still triggered in the inspector and can trigger your callback methods, displaying an error message.

The field previous value of a variable can be useful in some cases, like in this example to determine whether the player has been healed or if it has taken damage.

Last updated