Unity does not support serializing Dictionary types out of the box because it does not handle generic types directly. To make a dictionary serializable in the Inspector, you must create a custom class that inherits from Dictionary and implements the ISerializationCallbackReceiver interface.

This custom class uses two hidden [SerializeField] lists (one for keys and one for values) to store the data, converting the dictionary into a format Unity can save. You must then define specific concrete subclasses (e.g., SerializableDictionary<string, int>) to work with your desired key and value types.

Implementation Pattern

The standard approach involves implementing OnBeforeSerialize to populate the lists from the dictionary and OnAfterDeserialize to reconstruct the dictionary from the lists.

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

[System.Serializable]
public class SerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, ISerializationCallbackReceiver
{
    [SerializeField]
    private List<TKey> keys = new List<TKey>();
    
    [SerializeField]
    private List<TValue> values = new List<TValue>();

    // Convert dictionary to lists for Unity serialization
    public void OnBeforeSerialize()
    {
        keys.Clear();
        values.Clear();
        foreach (var pair in this)
        {
            keys.Add(pair.Key);
            values.Add(pair.Value);
        }
    }

    // Rebuild dictionary from lists after deserialization
    public void OnAfterDeserialize()
    {
        this.Clear();
        if (keys.Count != values.Count)
        {
            throw new System.Exception("There are " + keys.Count + " keys and " + values.Count + " values after deserialization. Make sure that both key and value types are serializable.");
        }

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

// Concrete subclass required because Unity cannot serialize generic types directly
[System.Serializable]
public class StringIntDictionary : SerializableDictionary<string, int>
{
}

Alternative Solutions

  • Odin Inspector: The Odin Inspector asset automatically serializes dictionaries by inheriting from SerializedScriptableObject or using their serializer without custom code.

  • SerializedDictionary Package: A popular third-party asset (e.g., AYellowpaper.SerializedCollections) provides a SerializedDictionary<,> class that feels native to the Unity Editor and supports features like duplicate keys and bulk editing.

  • JSON Serialization: For runtime-only scenarios, you can serialize the dictionary to a JSON string using JsonUtility (with a wrapper class) or Json.NET (Newtonsoft), though this does not show in the Inspector by default.

  • Custom Property Drawer: You can create a custom PropertyDrawer to draw a Dictionary in the Inspector manually, allowing editing without changing the underlying data structure to a serializable list.

Just use this in place of any dictionary you need to be serializeable. using System.Collections.Generic; using UnityEngine; [System.Serializable] public class SerializableDictionary : Dictionary, ISerializationCallbackReceiver { [SerializeField] private List m_Keys = new List(); [SerializeField] private List m_Values = new List(); public void OnBeforeSerialize() { m_Keys.Clear(); m_Values.Clear(); using Enumerator enumerator = GetEnumerator(); while (enumerator.MoveNext()) { KeyValuePair current = enumerator.Current; m_Keys.Add(current.Key); m_Values.Add(current.Value); } } public void OnAfterDeserialize() { Clear(); for (int i = 0; i < m_Keys.Count; i++) { Add(m_Keys[i], m_Values[i]); } m_Keys.Clear(); m_Values.Clear(); } } Answer from foodeyemade on reddit.com
🌐
Unity
discussions.unity.com › questions & answers
[Solved]How to serialize Dictionary with Unity Serialization System - Questions & Answers - Unity Discussions
May 21, 2013 - Edit: http://forum.unity3d.com/threads/finally-a-serializable-dictionary-for-unity-extracted-from-system-collections-generic.335797/ Hello everyone, I already read many things about Serialization with Unity and i already know that Dictionary are not serialized by Unity.
🌐
Reddit
reddit.com › r/unity3d › why doesn't unity serialize dictionaries???
r/Unity3D on Reddit: Why doesn't Unity serialize Dictionaries???
October 29, 2024 -

Dictionaries are just better resilent arrays with a search complexity O(1). I was working with scriptable objects and found out the hard way that unity doesnt save variables in scriptable objects that cannot be serialized. Had to use Odin Inspector's custom scriptable object for a quick workaround.

I'm sure theres a good reason to not serialize dictionaries... but cant think of any reason not to.

Discussions

Can't I serialize the Dictionary used by Unity? - Stack Overflow
I want to see the Dictionary used by Unity on the Inspector. But I don't know if it's possible or not, and I don't know how. Please tell me how to see the Dictionary on the inspector. Or you can te... More on stackoverflow.com
🌐 stackoverflow.com
Add built-in serialization-support for dictionaries(with editor)
Currently, my projects always depend on external or self-written solutions like this asset: Serialized Dictionary | Utilities Tools | Unity Asset Store. Despite their usability, it’s hard to trust and maintain these solutions. Therefore, it would be perfect to have such a feature built-i... More on discussions.unity.com
🌐 discussions.unity.com
0
2
May 21, 2024
Finally, a serializable dictionary for Unity! (extracted from System.Collections.Generic) - Unity Engine - Unity Discussions
Hey guys, so as all you all know Unity doesn’t know how to serialize generic dictionaries. Since 4.6 we got the ISerializationCallbackReceiver which allows us to use custom serialization to serialize types that Unity cannot. However; when using this interface to serialize dictionaries it’s ... More on discussions.unity.com
🌐 discussions.unity.com
29
June 24, 2015
Netcode INetworkSerializable for Dictionarys
I am trying to Use a Dictionary in a Rpc with Netcode. public void NetworkSerialize (BufferSerializer serializer) where T : IReaderWriter { serializer.SerializeValue(ref exampleDictionary); } But it says that it cant serialize it (“The type ‘Dictionary ’ must be a non-nullable value type, ... More on discussions.unity.com
🌐 discussions.unity.com
0
0
March 3, 2022
🌐
GitHub
github.com › ayellowpaper › SerializedDictionary
GitHub - ayellowpaper/SerializedDictionary · GitHub
Serialized Dictionary will serialized any Unity serializable type, including Unity Objects like transforms and ScriptableObjects. Furthermore, it allows to serialize duplicate keys and null values.
Starred by 141 users
Forked by 20 users
Languages   C#
🌐
Unity Asset Store
assetstore.unity.com › home › tools › utilities › serialized dictionary
Serialized Dictionary | Utilities Tools | Unity Asset Store
October 22, 2024 - Use the Serialized Dictionary from ayellowpaper on your next project. Find this utility tool & more on the Unity Asset Store.
Find elsewhere
🌐
Odin Inspector
odininspector.com › tutorials › serialize-anything › serializing-dictionaries
Serializing Dictionaries | Odin Inspector for Unity
public MyScriptableObject : ... Unity does not support Dictionary serialization out of the box, but by exploiting Unity's serialization protocol (See On Unitys Serialization Procotol) it can be done....
🌐
Unity
discussions.unity.com › unity engine
Add built-in serialization-support for dictionaries(with editor) - Unity Engine - Unity Discussions
May 21, 2024 - Add the ability to serialize dictionaries with the built-in editor. This feature is important for creating user-friendly configurations through scriptable objects and sometimes for configuring mono-behaviours. Currently, my projects always depend on external or self-written solutions like this asset: Serialized Dictionary | Utilities Tools | Unity Asset Store.
🌐
Unity
discussions.unity.com › unity engine
Finally, a serializable dictionary for Unity! (extracted from System.Collections.Generic) - Unity Engine - Unity Discussions
June 24, 2015 - Hey guys, so as all you all know Unity doesn’t know how to serialize generic dictionaries. Since 4.6 we got the ISerializationCallbackReceiver which allows us to use custom serialization to serialize types that Unity ca…
🌐
Unity
discussions.unity.com › unity engine
Netcode INetworkSerializable for Dictionarys - Unity Engine - Unity Discussions
March 3, 2022 - I am trying to Use a Dictionary in a Rpc with Netcode. public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter { serializer.SerializeValue(ref exampleDictionary); …
🌐
Unity
discussions.unity.com › unity engine
JsonUtility can't serialize Dictionary - Unity Engine - Unity Discussions
March 22, 2021 - Why, Unity? Like… it’s a dictionary!! It’s literally a json! I’d understand if I was asking something vastly complicated and you were like “nah, dude, too hard”. But it’s a dictionary! Why can’t you just loop over keys a…
🌐
Unity
discussions.unity.com › unity engine
20 lines to serialize any type in Unity (Dictionaries, nested lists, etc) - Unity Engine - Unity Discussions
August 21, 2015 - I needed to serialize a Dictionary<int, List> for a MonoBehaviour that also executes in the editor, and I discovered the (well known, as it turns out) limitations of the Unity serializer. I found some solutions on the fo…
🌐
Unity
docs.unity3d.com › 2020.1 › Documentation › Manual › JSONSerialization.html
Unity - Manual: JSON Serialization
When you pass in an object to the standard Unity serializer for processing, the same rules and limitations apply as they do in the Inspector: Unity serializes fields only; and types like Dictionary<> are not supported.
🌐
Unity
discussions.unity.com › questions & answers
Dictionary in inspector - Questions & Answers - Unity Discussions
February 17, 2014 - We all know Dictionaries do not appear in the Editor. What would be a way to get them to appear? Suppose I have: [Serializable] public class MySerializableObject { public float Name; public float Description; } public Dictionary MyDictionary; Strings and Serializable objects both appear in ...
🌐
Qiita
qiita.com › c#
実はあったSerializedDictionary #C# - Qiita
June 30, 2023 - Unityで開発している際に「DictionaryをSerializeしたいな」とか「DictionaryをJson化したいな」と思うことありますよね。(私はありました) ただ、SerializeするにはGoogleで調べた限りPairをListで作ってSerializeDictionaryというようなクラスを自作で用意する必要がありそうでした。
🌐
Code Maze
code-maze.com › home › how to serialize a dictionary to json in c#
How to Serialize a Dictionary to JSON in C# - Code Maze
May 17, 2023 - We just need to create a custom converter and add it to our serializer options declaration: public sealed class SystemJsonCustomerInvoiceConverter : JsonConverter<Dictionary<Customer, List<Invoice>>> { public override void Write(Utf8JsonWriter writer, Dictionary<Customer, List<Invoice>> value, JsonSerializerOptions options) { writer.WriteStartObject(); foreach (var (customer, invoices) in value) { writer.WritePropertyName($"Customer-{customer.CustomerId:N}"); writer.WriteStartObject(); WriteCustomerProperties(writer, customer); WriteInvoices(writer, invoices); writer.WriteEndObject(); } writer.WriteEndObject(); } // Omitted for brevity }
🌐
Unity
discussions.unity.com › questions & answers
How to serialize a Dictionary? - Questions & Answers - Unity Discussions
March 23, 2015 - I’m trying to modify the TagFrenzy plugin to use a dictionary instead of a list for the tags. The issue I’m running into is that the Dictionary is not being found when I try and use mySerializedDictionary = tagger.FindProperty("MyDictionary"); If I replace “MyDictioanry” with a list of the same name it is found.
🌐
Unity
discussions.unity.com › unity engine
Best practices for Generic.Dictionary Serialization? - Unity Engine - Unity Discussions
December 6, 2013 - Hello, I’ve run into a bit of a wall with my current project. I’m storing stuff in a Vector2,Node Dictionary, wherein both Vector2 and Node are custom classes. I’ve read a lot of stuff about this in the past month. Solutions other people say work should be : Make Dictionary non generic by inheritance.