Mirror
  • Mirror Networking
  • API Reference
  • Development Blog
    • A Brief History of Mirror
  • User Manual
    • General
      • Getting Started
      • Script Templates
      • Change Log
        • 2024 Change Log
        • 2023 Change Log
        • 2022 Change Log
        • 2021 Change Log
        • 2020 Change Log
        • 2019 Change Log
      • Deprecations
      • Migration Guide
      • Integrations
      • Timestamp Batching
      • TCP and UDP
      • CCU
      • SyncDirection
      • Round Trip Time (RTT)
      • Connection Quality
      • Lag Compensation
      • Client Side Prediction
      • History Bounds
      • Tests
      • NetGraph
    • FAQ
      • Execution Order
    • Transports
      • KCP Transport
      • Telepathy Transport
      • WebSockets Transport
        • Reverse Proxy
          • Windows
            • IIS
          • Linux
            • NGINX
            • Caddy
            • Apache
            • HA Proxy
        • SSL
      • Multiplex Transport
      • Latency Simulation Transport
      • Ignorance
      • LiteNetLib Transport
      • FizzySteamworks Transport
      • FizzyFacepunch Transport
      • Encryption Transport
      • Edgegap Transports
        • Edgegap Relay
        • Edgegap Lobby
    • Components
      • Network Animator
      • Network Authenticators
        • Basic Authenticator
        • Device Authenticator
      • Network Behaviour
      • Network Discovery
      • Network Identity
      • Network Manager
      • Network Manager HUD
      • Network Ping Display
      • Network Profiler
      • Network Rigidbody
      • Network Lerp Rigidbody
      • Network Room Manager
      • Network Room Player
      • Network Start Position
      • Network Statistics
      • Remote Statistics
      • Network Transform
        • Snapshot Interpolation
      • Deprecated
        • Network Proximity Checker
        • Network Scene Checker
        • Network Match Checker
        • Network Owner Checker
    • Interest Management
      • Spatial Hashing
      • Distance
      • Scene
      • Scene + Distance
      • Match
      • Team
      • Custom
      • Legacy
    • Guides
      • Authority
      • IDs
      • Attributes
      • Time Synchronization
      • Data types
      • Serialization
      • Synchronization
        • SyncVars
        • SyncVar Hooks
        • SyncEvent (Obsolete)
        • SyncLists
        • SyncDictionary
        • SyncHashSet
        • SyncSortedSet
      • Communications
        • Remote Actions
        • NetworkManager Callbacks
        • NetworkBehaviour Callbacks
        • Network Messages
      • GameObjects
        • Player Game Objects
        • Custom Character Spawning
        • Custom Spawn Functions
        • Scene GameObjects
        • Pickups, Drops, and Child Objects
    • Examples
      • Additive Levels
      • Additive Scenes
      • Basic
      • Billiards
      • Multiple Additive Scenes
      • Pong
      • Room
      • Tanks
      • EdgegapLobby
  • Server Hosting
    • The Pragmatic Hosting Guide
    • Cloud Hosting Guides
      • AWS
      • Google Cloud
      • Oracle Free Tier
    • Hosting with a Remote Desktop
    • Edgegap Hosting Plugin Guide
  • Security
    • Security Overview
    • Cheat Protection Stages
    • Cheats & Anticheats
  • Community Guides
    • Community Translations
    • Video Tutorials
    • Resources
    • Mirror Quick Start Project
    • Unity for MMORPGs
    • Unity Canvas HUD
    • Odin Inspector Support
    • Ready Up And Die!
    • iOS AppStore
    • Mirror Docker Guide
    • Gitbook Guide
    • Mirror Branding
    • Contributors Agreement
    • Documentation License
Powered by GitBook
On this page
  • Usage
  • Simple Example
  1. User Manual
  2. Guides
  3. Synchronization

SyncDictionary

PreviousSyncListsNextSyncHashSet

Last updated 6 months ago

A SyncDictionary is an associative array containing an unordered list of key, value pairs. Keys and values can be any . By default we use .Net which may impose additional constraints on the keys and values.

SyncDictionary works much like : when you make a change on the server the change is propagated to all clients and the appropriate Actions are invoked. Only deltas are transmitted.

Usage

SyncDictionary must be declared readonly and initialized in the constructor.

Note that by the time you wire up the Action handlers, the dictionary will already be initialized, so they will not get invoked for the initial data, only updates.

Simple Example

using System.Collections.Generic;
using UnityEngine;
using Mirror;

public enum Slots : byte { head, body, feet, hands }

public struct Item
{
    public string name;
    public int hitPoints;
    public int durability;

    public Item(string name, int hitPoints, int durability)
    {
        this.name = name;
        this.hitPoints = hitPoints;
        this.durability = durability;
    }

    public override string ToString()
    {
        return $"name={name} hitPoints={hitPoints} durability={durability}";
    }
}

public class SyncDictionaryExample : NetworkBehaviour
{
    public readonly SyncDictionary<Slots, Item> Equipment = new SyncDictionary<Slots, Item>();

    public override void OnStartServer()
    {
        Equipment[Slots.head] = new Item("Helmet", 10, 20);
        Equipment[Slots.body] = new Item("Epic Armor", 50, 50);
        Equipment[Slots.feet] = new Item("Sneakers", 3, 40);
        Equipment[Slots.hands] = new Item("Sword", 30, 15);
    }

    public override void OnStartClient()
    {
        // Add handlers for SyncDictionary Actions
        Equipment.OnAdd += OnItemAdded;
        Equipment.OnSet += OnItemChanged;
        Equipment.OnRemove += OnItemRemoved;
        Equipment.OnClear += OnDictionaryCleared;

        // OnChange is a catch-all event that is called for any change
        // to the dictionary. It is called after the specific events above.
        // Strongly recommended to use the specific events above instead!
        Equipment.OnChange += OnDictionaryChanged;

        // Dictionary is populated before handlers are wired up so we
        // need to manually invoke OnAdd for each element.
        foreach (Slots key in Equipment.Keys)
            Equipment.OnAdd.Invoke(key);
    }

    public override void OnStopClient()
    {
        // Remove handlers when client stops
        Equipment.OnAdd -= OnItemAdded;
        Equipment.OnSet -= OnItemChanged;
        Equipment.OnRemove -= OnItemRemoved;
        Equipment.OnClear -= OnDictionaryCleared;
        Equipment.OnChange -= OnDictionaryChanged;
    }

    void OnItemAdded(Slots key)
    {
        Debug.Log($"Element added {key} {Equipment[key]}");
    }

    void OnItemChanged(Slots key, Item oldValue)
    {
        Debug.Log($"Element changed {key} from {oldValue} to {Equipment[key]}");
    }

    void OnItemRemoved(Slots key, Item oldValue)
    {
        Debug.Log($"Element removed {key} {oldValue}");
    }

    void OnDictionaryCleared()
    {
        // OnDictionaryCleared is called before the dictionary is actually cleared
        // so we can iterate the dictionary to get the elements if needed.
        foreach (KeyValuePair<Slots, Item> kvp in Equipment)
            Debug.Log($"Element cleared {kvp.Key} {kvp.Value}");
    }

    // OnDictionaryChanged is a catch-all event that is called for any change
    // to the dictionary. It is called after the specific events above.
    //
    // NOTE: It's strongly recommended to use the specific events above instead!
    //
    // For OP_ADD, the value param is the NEW entry.
    // For OP_SET, the value param is the OLD entry.
    // For OP_REMOVE, the value param is the OLD entry.
    // For OP_CLEAR, the value param is null / default.
    void OnDictionaryChanged(SyncDictionary<Slots, Item>.Operation op, Slots key, Item value)
    {
        switch (op)
        {
            case SyncDictionary<Slots, Item>.Operation.OP_ADD:
                // value is the new entry
                Debug.Log($"Element added {key} {value}");
                break;

            case SyncDictionary<Slots, Item>.Operation.OP_SET:
                // value is the old entry
                Debug.Log($"Element set {key} from {value} to {Equipment[key]}");
                break;

            case SyncDictionary<Slots, Item>.Operation.OP_REMOVE:
                // value is the old entry
                Debug.Log($"Element removed {key} {value}");
                break;

            case SyncDictionary<Slots, Item>.Operation.OP_CLEAR:
                // value is null / default
                // we can iterate the dictionary to get the elements if needed.
                foreach (KeyValuePair<Slots, Item> kvp in Equipment)
                    Debug.Log($"Element cleared {kvp.Key} {kvp.Value}");
                break;
        }
    }
}
public class ExamplePlayer : NetworkBehaviour
{
    public readonly SyncIDictionary Equipment = 
        new SyncIDictionary(new SortedList());
}

By default, SyncDictionary uses a to store it's data. If you want to use a different IDictionary implementation such as or , then use SyncIDictionary and pass the dictionary instance you want it to use. For example:

supported mirror type
Dictionary
SyncLists
Dictionary
SortedList
SortedDictionary