SNetworkVariable

Network variables are an alternative to network actions, but achieve a very similar thing.

The main difference is that the variable refresh can be executed automatically instead of having to manually call Trigger().

Defining Variables

You can define a class variable and then link it inside OnSpawn

private SNetworkVariable<BoxSync> sync_state = new SNetworkVariable<BoxSync>();
protected override void OnSpawn()
{
    sync_state.Init(this, "refresh", NetworkDelivery.UnreliableSequenced, NetworkActionTarget.Clients);
    sync_state.AutoRefresh(true, sync_refresh_rate); //Set the refresh rate
}

protected override void OnDespawn()
{
    sync_state.Clear();
}

Read / Write the variable

You can access the variable value with

sync_state.value

The reason why in the example the variable is instantiated before OnSpawn is so that .value can be accessed even if the object is not spawned. Instead we call Init() inside OnSpawn to link it to the network.

onReceive, onSend

You can optionally define a callback to be called whenever the variable refresh is received or sent.

sync_state.onReceive = OnReceive;
sync_state.onSend = OnSend;

Delivery, Target, and Authority

These work exactly the same way as SNetworkActions. But unlike actions, the default values are different.

Default target is All for actions and Clients for variables.

Default delivery is Reliable for actions and UnreliableSequenced for variables.

Authority is also based on who is the owner.

Last updated