Nice ways to serialize Dictionary<string,object> or List<string, object>

I’ve been serializing and saving dictionaries and lists that use strings as keys to store various kinds of data by doing KVP stuff. The sorta stuff below

I’m under the impression that there’s a far better way to do this but I can’t figure out how! Either some kind of thing I can use to handle the serialization or a file type or something. If someone can point me to where I’d find something like that I’d be very thankful!

There’s an example in Unity’s own docs: Unity - Scripting API: ISerializationCallbackReceiver

Generally all inline custom serialisation happens via the ISerialisationCallbackReciever interface.

Definitely no need to use XML.

1 Like

I have a script called serializable dictionary I found in a tutorial in which I call instead of dictionary.

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

[System.Serializable]
public class SerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, ISerializationCallbackReceiver
{
    [SerializeField] List<TKey> keys = new List<TKey>();
    [SerializeField] List<TValue> values = new List<TValue>();
    public void OnBeforeSerialize()
    {
        keys.Clear();
        values.Clear();
        foreach (KeyValuePair<TKey, TValue> pair in this)
        {
            keys.Add(pair.Key);
            values.Add(pair.Value);
        }
    }
    public void OnAfterDeserialize()
    {
        this.Clear();
        for (int i = 0; i < keys.Count; i++)
        {
            this.Add(keys[i], values[i]);
        }
    }
}
1 Like