2019-03-22 13:51:29 +00:00
# SyncHashSet
2019-06-25 05:59:13 +00:00
`SyncHashSet` are sets similar to C\# [HashSet\<T\> ](https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.hashset-1 ) that synchronize their contents from the server to the clients.
2019-03-30 16:51:06 +00:00
A SyncHashSet can contain items of the following types:
- Basic type (byte, int, float, string, UInt64, etc)
2019-06-25 05:59:13 +00:00
2019-03-30 16:51:06 +00:00
- Built-in Unity math type (Vector3, Quaternion, etc)
2019-06-25 05:59:13 +00:00
2019-03-30 16:51:06 +00:00
- NetworkIdentity
2019-06-25 05:59:13 +00:00
- Game object with a NetworkIdentity component attached.
2019-03-30 16:51:06 +00:00
- Structure with any of the above
## Usage
2019-06-25 05:59:13 +00:00
Create a class that derives from SyncHashSet for your specific type. This is necessary because Mirror will add methods to that class with the weaver. Then add a SyncHashSet field to your NetworkBehaviour class. For example:
2019-03-30 16:51:06 +00:00
2019-07-07 05:52:37 +00:00
```cs
2019-03-30 16:51:06 +00:00
class Player : NetworkBehaviour {
class SyncSkillSet : SyncHashSet< string > {}
2019-08-19 21:54:51 +00:00
readonly SyncSkillSet skills = new SyncSkillSet();
2019-03-30 16:51:06 +00:00
int skillPoints = 10;
[Command]
public void CmdLearnSkill(string skillName)
{
if (skillPoints > 1)
{
skillPoints--;
skills.Add(skillName);
}
}
}
```
2019-08-19 21:54:51 +00:00
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.
2019-08-20 13:29:55 +00:00
> Note that by the time you subscribe, the set will already be initialized, so you will not get a call for the initial data, only updates.</p>
>Note SyncSets must be initialized in the constructor, not in Startxxx(). You can make them readonly to ensure correct usage.
2019-03-30 16:51:06 +00:00
2019-07-07 05:52:37 +00:00
```cs
2019-03-30 16:51:06 +00:00
class Player : NetworkBehaviour
{
class SyncSetBuffs : SyncHashSet< string > {};
2019-08-19 21:54:51 +00:00
public readonly SyncSetBuffs buffs = new SyncSetBuffs();
2019-03-30 16:51:06 +00:00
// 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;
}
void OnBuffsChanged(SyncSetBuffs.Operation op, string buff)
{
switch (op)
{
case SyncSetBuffs.Operation.OP_ADD:
// we added a buff, draw an icon on the character
break;
case SyncSetBuffs.Operation.OP_CLEAR:
// clear all buffs from the character
break;
case SyncSetBuffs.Operation.OP_REMOVE:
// We removed a buff from the character
break;
}
}
}
```