Change Detection
Overview
When using Networked Properties a common use case is to have code executed whenever the value of a Networked Property changes.
OnChangedRender
The OnChangedRender
attribute is the easiest way for handling Render
based Change Detection.
To detect changes on a Networked Property, add a OnChangedRender
attribute to it. The attribute takes a method name. The given method needs to be a void function on the same NetworkBehaviour
.
IMPORTANT: OnChangedRender
is not called when the object is first spawned on a client. To initialize an object use the override Spawned
function and call your changed function from there or initialize the object manually.
Example:
C#
public class Example : NetworkBehaviour
{
[Networked, OnChangedRender(nameof(OnColorChanged))]
public Color NetworkedColor { get; set; }
public Material material;
public void OnColorChanged()
{
material.color = NetworkedColor;
}
}
nameof(OnColorChanged)
is used to provide the methode name string to the attribute instead of hard coding the name. This ensures that when refactoring the function name the attribute is updated with the new name automatically.Previous Value
Access to the previous value before the change occurred is possible.
C#
[Networked]
[OnChangedRender(nameof(CounterChanged))]
public int Counter { get; set; }
void CounterChanged(NetworkBehaviourBuffer previous)
{
var prevValue = GetPropertyReader<int>(nameof(Counter)).Read(previous);
Log.Info($"counter changed: {Counter}, prev: {prevValue}");
}
The type when calling GetPropertyReader<T>
needs to match the type of the Networked Property.