SNetworkBehaviour

SNetworkBehaviour should not be added directly as a component. When you create a new script that will use networking features, you should inherit from SNetworkBehaviour instead of MonoBehaviour.

public class Tank : SNetworkBehaviour

There are a few functions you can override

OnReady()

Will be triggered only after the NetcodePlus improved connection process has completed. This function will only be called once for each object, even if you spawn/despawn it multiple times. Use this function instead of Start() if you need to wait to have all the game data up to date before initializing the object. This function can trigger even if the object is not spawned yet, and can trigger before or after OnSpawn depending on when the object is spawned.

In other words, when instantiating a new object in an existing connected game, it will be called at the same time than Start() (depending on which script triggers its Start function first), but if the object exist before the connection is established, it won't be called until the connection process finishes transferring all the initialization data (see Connection Process page).

OnSpawn()

Called right after an object is spawned. Spawning is the process of starting to sync an object between server and client. If an object is not IsSpawned, it won't be synced. If it is it will. This function will be called multiple times on the same object if the object is despawned and spawned again (Like if using the SNetworkOptimizer and going in and out of range of the object).

OnDespawn()

Called just before an object is despawned. It will also be called if using the Destroy() function inside SNetworkObject (not the unity Destroy() function). Since that function will make sure the object is despawned before destroying it.

OnBeforeSpawn()

Called before spawning an object (on the server side only since the object doesn't exist yet on the client). This function can be useful if you want to send some custom data with the spawn request using SetSpawnData.

SpawnData

It is possible to add custom data to a Spawn.

To do this, you can write the data in OnBeforeSpawn and read it in OnSpawn

protected override void OnBeforeSpawn()
{
    TowerRefreshData sdata = new TowerRefreshData();
    sdata.player_id = player_id;
    sdata.hp = hp;

    SetSpawnData(sdata);
}
protected override void OnSpawn()
{
    TowerRefreshData sdata = GetSpawnData<TowerRefreshData>();
    player_id = sdata.player_id;
    hp = sdata.hp;
}

The data class must be INetworkSerializable

public class TowerRefreshData : INetworkSerializable
{
    public int player_id;
    public int hp;

    public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
    {
        serializer.SerializeValue(ref player_id);
        serializer.SerializeValue(ref hp);
    }
 }

Last updated