This document is about: FUSION 2
SWITCH TO

Change Detection

Overview

When using Networked Properties a common use case is to have code executed whenever the value of a Networked Property changes.

Fusion provides multiple ways of Change Detection:

Change Detection in Render: Often code that is run when a change is detected does not affect the gameplay simulation but instead exists for visual purposes only. Examples include updating a UI healthbar whenever a health Networked Property changes or updating the color of the player's mesh renderer whenever a color Networked Property changes.

Change Detection in FixedUpdateNetwork: In Host/Server Mode this is needed when the Change Detection is used to affect gameplay. For example the player's movement speed is reduced by 50% whenever the stamina Networked Property falls below 50. In these cases running Change Detection in FixedUpdateNetwork ensures that the client-side-prediction matches the server's simulation and allows for correct rollbacks.

Custom Change Detection: Change Detection can be run manually at custom intervals. This is rarely needed except in advanced use cases. Running Change Detection less frequently can slightly improve CPU performance.

In Shared Mode using Render based Change Detection is sufficient for most use cases.

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.

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.

ChangeDetector

A ChangeDetector provides more flexibility than the OnChangedRender attribute. Allowing for ChangeDetection in FixedUpdateNetwork or at a manual interval.

ChangeDectors are for advanced use cases. Documentation for ChangeDectors is available in the ChangeDetector section of the Network Buffers page in the advanced manual.

Back to top