Getting started
Hold a value, react to it, and share it with another behaviour.
Hold a value
An Observable<T> is a field like any other. Create it where you declare it, so it exists before anything subscribes:
using Udonite.Observables;
using Udonite;
using UnityEngine;
public class Match : UdoniteBehaviour
{
private Observable<int> score = new Observable<int>();
public void Award()
{
score.Value = score.Value + 1;
}
}
Nothing happens yet, because nobody is listening.
React to it
A subscriber is an ordinary method taking the value:
public override void Start()
{
score.Subscribe(OnScoreChanged, true);
}
private void OnScoreChanged(int value)
{
label.text = value.ToString();
}
The true is worth understanding. It calls this handler and nobody else, immediately, with the value as it stands. That is how a behaviour joining late catches up. Without it the handler waits for the next change, and a scoreboard that starts after the first goal shows nothing until the second.
Share it with another behaviour
The observable is an object, so a second behaviour can hold the same one:
public class Announcer : UdoniteBehaviour
{
public Match match;
public override void Start()
{
match.Score.Subscribe(OnScoreChanged, true);
}
private void OnScoreChanged(int value) { /* ... */ }
}
Expose it as ISubscribable<int> rather than Observable<int> and the announcer can subscribe but cannot set:
public ISubscribable<int> Score => score;
It is local, not synced
Changing an observable on your client tells your client's subscribers and nobody else's. There is no networking in this package.
To share a value, sync it the way you always would and drive the observable from the callback:
private Synced<int> syncedScore = new Synced<int>();
public override void Start()
{
syncedScore.Subscribe(OnScoreArrived);
}
private void OnScoreArrived(int value)
{
score.Value = value;
}
Because setting the same value notifies nobody, a deserialization that did not change the score costs one comparison and no callbacks.
Where to go next
Notification rules covers subscribing, unsubscribing and writing during a notification, including the one thing Udon refuses outright.