Skip to main content

Network Snapshot

Network snapshot is a concept that can be used to initialize something when a client joins a game session in the middle of the session. In order to use this feature, NetworkIdentity is required to be added to the GameObject that implements the ISnapshot interface. NetworkIdentity guarantees that the position and rotation of a GameObject will be initialized with the latest available information from the host. When it is required to have more data to be sent during the instantiation process, network snapshots will be useful.

Implementing Network Snapshot

To implement a network snapshot, first we need to look at the ISnapshot interface.

public interface ISnapshot
{
void EnqueueSnapshot(BaseHostMessageHandler hostMsg);
void RegisterSnapshotCallback(BaseHostMessageHandler hostMsg);
}

In order to setup a network snapshot, it is required to implement the ISnapshot interface. There are two methods that needs to be implemented, EnqueueSnapshot and RegisterSnapshotCallback.

In the sample project, there is a PlayerIdManager class that takes care of managing the id of different players. Do note that this id is a logical representation in the game logic for each player, and it is different than Player.UserNumber. This id is used to assign a color to the players' character.

Take a look at how this concept is used within the PlayerIdManager class.

using PretiaArCloud.Networking;
using MessagePack;

// Define a network message type for the snapshot
[NetworkMessage]
[MessagePackObject]
public class PlayerIdSnapshotMsg : BaseNetworkMessage
{
[Key(0)]
public uint?[] UserNumbers;
}

public class PlayerIdManager : MonoBehaviour, ISnapshot
{
private uint?[] _userNumbers;

// The actual player id management implementation is omitted for brevity.

// Implements EnqueueSnapshot
public void EnqueueSnapshot(HostToPlayerMessageHandler hostToPlayerMsg)
{
// Within this function, developers only need to call hostMsg.Enqueue
// followed with the snapshot message.
hostToPlayerMsg.Enqueue(new PlayerIdSnapshotMsg { UserNumbers = _userNumbers });
}

public void RegisterSnapshotCallback(HostToPlayerMessageHandler hostToPlayerMsg)
{
// Within this function, developers only need to register an initialization callback
// to the snapshot message type
hostToPlayerMsg.Register<PlayerIdSnapshotMsg>(SetupUserNumbers);
}

private void SetupUserNumbers(PlayerIdSnapshotMsg msg)
{
// Do initialization process
}
}