Observe changes
Observe runs your code each time a member's value changes, from a modifier or a plain write. It
works on any field or property, your own or Unity's, with or without modifiers on it.
Observe a member
Call Observe on the member, with a handler that takes the new value:
using Concordance;
using UnityEngine;
public class VolumeLabel : MonoBehaviour
{
void OnEnable() => AudioListener.volume.Observe(OnVolumeChanged);
void OnVolumeChanged(float volume) => Debug.Log($"Volume: {volume}");
}
When a handler throws, Concordance logs the exception, and the other handlers still run. A handler can't write the member it observes, or set a modifier on it: that throws, since each write would call the handler again. To keep a value in range, use a modifier instead.
Observe works in Play mode and while a Test Runner test runs,
as modifiers do.Receive the previous value
To receive the previous value too, pass a handler that takes two parameters, the previous value then the new one:
AudioListener.volume.Observe(OnVolumeChanged);
void OnVolumeChanged(float previous, float volume) => Debug.Log($"Volume: {previous} to {volume}");
Stop observing
An observer ends when its owner, the object that called Observe, is destroyed. To stop earlier, such
as while the object is disabled, call StopObserving with the same handler, and the same owner if you
passed one:
void OnDisable() => AudioListener.volume.StopObserving(OnVolumeChanged);
An owner that isn't a Unity object ends its observers when the garbage collector collects it.
End an observer with another object
To end an observer when another object is destroyed, pass that object as its owner:
player.health.Observe(OnHealthChanged, owner: healthBar); // ends when healthBar is destroyed