It is often useful to know when a synced property has changed its value. It can be easily achieved using the OnValueSyncedAttribute
. This attribute lets you define a method that will be called each time a value of a synced member (field or property) changes in the non-simulated version of an entity.
Let's start with a simple example:
Whenever the value of the Health
field gets updated (synced with its simulated version) the UpdateHealthLabel
will be called automatically, changing the health label text and printing log with a health difference.
This comes in handy in projects that use authoritative simulators. The client code can easily react to changes in the Player
entity state introduced by the simulator, updating the visual representation (which the simulator doesn't need).
The OnValueSyncedAttribute
requires using baked scripts.
Remember that the callback method will be called only for a non-simulated instance of an entity. Use on a simulated (owned) instance requires calling the selected method manually whenever the value of a given field/member changes. We recommend using properties with a backing field for this.
The OnValueSynced
feature can be used only on members of user-defined types, that is, there's no way to be notified about a change in the value of a Unity type member, like transform.position
. This might however change in the future, so stay tuned!