SyncHashSet

SyncHashSet are sets similar to C# HashSet that synchronize their contents from the server to the clients.

A SyncHashSet can contain any supported mirror type

Usage

SyncHashSet must be declared readonly and initialized in the constructor.

Add a SyncHashSet field to your NetworkBehaviour class. For example:

public class Player : NetworkBehaviour
{
    [SerializeField]
    public readonly SyncHashSet<string> skills = new SyncHashSet<string>();

    int skillPoints = 10;

    [Command]
    public void CmdLearnSkill(string skillName)
    {
        if (skillPoints > 1)
        {
            skillPoints--;
            skills.Add(skillName);
        }
    }
}

You can also detect when a SyncHashSet changes. This is useful for refreshing your character in the client or determining when you need to update your database.

Subscribe to the Callback event typically during Start, OnClientStart or OnServerStart for that.

Note that by the time you subscribe, the set will already be populated, so you will not get a call for the initial data, only updates.

public class Player : NetworkBehaviour
{
    [SerializeField]
    public readonly SyncHashSet<string> buffs = new SyncHashSet<string>();

    // this will add the delegate on the client.
    // Use OnStartServer instead if you want it on the server
    public override void OnStartClient()
    {
        buffs.Callback += OnBuffsChanged;

        // Process initial SyncHashSet payload
        foreach (string buff in buffs)
            OnBuffsChanged(SyncSet<string>.Operation.OP_ADD, buff);
    }

    // SyncHashSet inherits from SyncSet so use SyncSet here
    void OnBuffsChanged(SyncSet<string>.Operation op, string buff)
    {
        switch (op)
        {
            case SyncSet<string>.Operation.OP_ADD:
                // Added a buff to the character
                break;
            case SyncSet<string>.Operation.OP_REMOVE:
                // Removed a buff from the character
                break;
            case SyncSet<string>.Operation.OP_CLEAR:
                // Cleared all buffs from the character
                break;
        }
    }
}

Last updated