Homebound / Scripts / DataHandling / SerializableDictionary.cs
SerializableDictionary.cs
Raw
using System;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// Serialization equivalent for the Dictionary to Json
/// </summary>
/// <typeparam name="TKey">ID for Value</typeparam>
/// <typeparam name="TValue">Value</typeparam>
[Serializable]
public class SerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, ISerializationCallbackReceiver
{
    [SerializeField] List<TKey> keys = new();
    [SerializeField] List<TValue> values = new();

    /// <summary>
    /// Clears and and then adds from the callback from Unity when deserializing the objects in the scene using SerializableDictionary
    /// </summary>
    public void OnBeforeSerialize()
    {
        keys.Clear();
        values.Clear();
        foreach (KeyValuePair<TKey, TValue> pair in this)
        {
            keys.Add(pair.Key);
            values.Add(pair.Value);
        }
    }
    /// <summary>
    /// Dictionary is repurposed upon being serialized.
    /// </summary>
    /// <exception cref="ArgumentException">Keys and Values are not equivalent, unexpected behaviour</exception>
    public void OnAfterDeserialize()
    {
        this.Clear();

        if (keys.Count != values.Count)
            throw new ArgumentException("Number of Keys does not match number of Values");

        for (int i = 0; i < keys.Count; i++)
        {
            this.Add(keys[i], values[i]);
        }
    }
}