JDSherbert / Unity-Serializable-Dictionary

Custom C# Dictionary implementation, serializable by the Unity inspector.
https://linktr.ee/JDSherbert
MIT License
10 stars 2 forks source link
csharp csharp-code dictionary inspector serialization unity unity-3d unity-editor unity-scripts unity2d unity3d

image

Unity - Serializable Dictionary

Stars Badge Forks Badge Watchers Badge Issues Badge



Extension Tool For Unity

License


Overview

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!

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. I've tried my best to replicate the default Dictionary featureset but there may be some variance.

Features:

Usage:

  1. Simply add this script to your project.
  2. If you haven't got it, I'd recommend grabbing Odin Inspector to make it look prettier!

Example Usage:

using UnityEngine;
using Sherbert.Framework.Generic;

public class DictionaryExample : MonoBehaviour
{
    [SerializeField] private SerializableDictionary<string, int> myDictionary = new();
}

Prerequisites

If you haven't got it, I'd strongly recommend grabbing Odin Inspector to make your serialized variables look prettier. You can grab Odin from here: