Network Synchronization

Spatial Multiplayer provides two main ways for synchronizing state and events:

  • Network Variables for synchronizing state between clients.
  • Remote Events for synchronizing events between clients.

Network Variables

Network Variables are used in conjunction with Network Behaviours to define shared state between clients.

public class ExampleBehaviour : SpatialNetworkBehaviour
{
// Changes to this variable will be synchronized across all clients
private NetworkVariable<int> _health = new(initialValue: 100);

public override void Spawned()
{
Debug.Log($"Player spawned with health: {_health.value}");
}
}
public class ExampleBehaviour : SpatialNetworkBehaviour
{
// Changes to this variable will be synchronized across all clients
private NetworkVariable<int> _health = new(initialValue: 100);

public override void Spawned()
{
Debug.Log($"Player spawned with health: {_health.value}");
}
}

Remote Events

Remote Events are used to trigger events on all clients, these are basic messages with custom payloads.

public class RemoteEventsExample : MonoBehaviour
{
private const byte EVENT_ID = 1;

private void Awake()
{
SpatialBridge.networkingService.remoteEvents.onEvent += OnRemoteEvent;
}

private void OnDestroy()
{
SpatialBridge.networkingService.remoteEvents.onEvent -= OnRemoteEvent;
}

private void OnRemoteEvent(NetworkingRemoteEventArgs args)
{
if (args.eventID == EVENT_ID)
{
string message = args.eventArgs[0] as string;
Debug.Log($"Received remote event with message: {message}");
}
}

public static void Trigger()
{
SpatialBridge.networkingService.remoteEvents.RaiseEventAll(EVENT_ID, "Hello World!");
}
}
public class RemoteEventsExample : MonoBehaviour
{
private const byte EVENT_ID = 1;

private void Awake()
{
SpatialBridge.networkingService.remoteEvents.onEvent += OnRemoteEvent;
}

private void OnDestroy()
{
SpatialBridge.networkingService.remoteEvents.onEvent -= OnRemoteEvent;
}

private void OnRemoteEvent(NetworkingRemoteEventArgs args)
{
if (args.eventID == EVENT_ID)
{
string message = args.eventArgs[0] as string;
Debug.Log($"Received remote event with message: {message}");
}
}

public static void Trigger()
{
SpatialBridge.networkingService.remoteEvents.RaiseEventAll(EVENT_ID, "Hello World!");
}
}