Dictionaries cannot be serialized and displayed in the Unity inspector as is. This pisses me off greatly, so I decided to write a quick and dirty code class to allow Dictionary Serialization in Unity.
Add this script to your project and discover the power of Dictionary Serialization.
Features:
- Allows Dictionary display in the inspector
- Allows values to be serialized.
Usage:
- Simply add this script to your project.
- Example Usage:
using UnityEngine;
using Sherbert.Framework.Generic;
public class DictionaryExample : MonoBehaviour
{
[SerializeField] private SerializableDictionary<string, int> myDictionary = new();
}
This Serializable Dictionary class is a custom implementation that allows you to have a dictionary-like data structure with key-value pairs that can be serialized and edited in the Unity editor. It addresses the limitation of Unity's default Dictionary class, which cannot be directly serialized. To create a Serializable Dictionary, you typically create a custom class derived from MonoBehaviour or ScriptableObject and define a dictionary field inside it. You then apply serialization attributes to the dictionary field to make it visible and editable in the Unity inspector.
To achieve serialization, the Serializable Dictionary class implements the ISerializationCallbackReceiver
interface. This interface provides two callback methods: OnBeforeSerialize()
and OnAfterDeserialize()
. It also implements the IDictionary
interface, allowing use of standard Dictionary behaviours.
By using the Serializable Dictionary class, you can easily create and manage key-value pairs directly in the Unity editor, allowing for dynamic customization and modification of data. This is particularly useful for scenarios where you need to store and modify structured data that should persist between editor sessions or during gameplay.
Note that while the Serializable Dictionary class provides a convenient way to work with serialized dictionaries in Unity, it is not a built-in Unity feature.