Dictionary serialization
Serialize Dictionary types.
Read time 14 minutesLast updated 16 days ago
Unity serializes fields declared as directly, so you can author dictionary data in scripts and edit it in the window without writing custom serialization code. The declared field type must be exactly .
Dictionary<TKey, TValue>Inspector
?
Dictionary<TKey, TValue>Dictionary serialization is opt-in: you must apply to each dictionary field that you want Unity to serialize. Unity only supports certain types as dictionary keys and values. The serialization rules analyzer detects unsupported key and value types at compile time and points to the rule that explains the limitation. The Inspector renders a two-column key/value editor with sort, duplicate-key detection, and column resizing.
[SerializeField]Unity serializes a dictionary as a sequence of key/value pairs in insertion order. The order shown in the Inspector is independent of the serialized order. Refer to Sort order in the Inspector.
Declare a serialized dictionary field
You can serialize a dictionary field on a , a , or any nested class or struct. Apply to a private or a public dictionary field, to make Unity serialize the dictionary:
MonoBehaviourScriptableObject[Serializable][SerializeField]using System.Collections.Generic;using UnityEngine;public class Inventory : MonoBehaviour{ [SerializeField] private Dictionary<string, int> itemCounts = new Dictionary<string, int>();}
Public dictionary fields aren't serialized automatically. Without , Unity skips the field, and the dictionary doesn't persist across domain reloads, scene saves, or Play mode transitions. The analyzer reports UAC1015 when a public dictionary field is missing , so you can decide whether to opt in or to mark the field .
[SerializeField][SerializeField][NonSerialized][SerializeReference][SerializeReference]Supported key and value types
Both and must be types that Unity can serialize:
TKeyTValue- Primitive types (,
int,float,double,bool).string - Enum types (32 bits or smaller).
- Unity built-in types, such as ,
Vector2,Vector3.Color - Custom classes and structs marked .
[Serializable] - References to types derived from .
UnityEngine.Object
Unity can't use an interface or an abstract type (other than a hierarchy), or a type that isn't marked , as a key or a value. The analyzer reports UAC1012 and UAC1016 respectively.
UnityEngine.Object[Serializable]Collections, such as a or an array, are valid as values but not as keys:
List<T>- As a value, you can use any supported type, or a collection of supported types such as a or an array. For example,
List<T>is valid.Dictionary<int, List<int>> - As a key, you can't use a type that implements - the interface that collection types such as
IEnumerableand arrays implement. TheList<T>type is an exception, even though it implementsstring. For example, Unity can't serialize aIEnumerablefield, because its key typeDictionary<List<int>, int>implementsList<int>. The analyzer reports UAC1013.IEnumerable
Unity also doesn't serialize a dictionary that's nested directly inside another collection. For example, and aren't supported. Wrap the dictionary in a class or struct that you can use as the element type. The analyzer reports this case as UAC1009.
List<Dictionary<string, int>>Dictionary<string, int>[][Serializable]Structs that contain a field — directly or anywhere in their field graph (including nested structs, class-typed fields, and the inheritance chains of those classes) — cannot be used as either a key or a value in a serialized dictionary. The analyzer reports UAC1019.
[SerializeReference]Classes that contain a field — directly or anywhere in their field graph or inheritance chain — cannot be used as dictionary keys. Classes with fields can still be used as dictionary values. The analyzer reports UAC1020.
[SerializeReference][SerializeReference]For the full set of analyzer rules and usage examples, refer to the serialization rules analyzer.
Custom struct and class keys
If you use a custom struct or class as a dictionary key, override and so the dictionary can place and find entries correctly:
GetHashCodeEquals- Custom classes without overrides use reference equality. Two instances with identical field values are treated as different keys, which breaks dictionary lookups.
- Custom structs without overrides fall back to reflection-based hashing and equality. The dictionary works correctly but is slow. Add overrides for better performance.
- Primitives, , enums, Unity built-in types such as
stringandVector3, andColorsubclasses already implementUnityEngine.ObjectandGetHashCodecorrectly. You don't need to override them.Equals
For value-type keys, also implement to avoid boxing allocations during key comparisons. isn't required, but it improves runtime performance.
IEquatable<T>IEquatable<T>If a custom or implementation throws an exception while Unity loads a serialized dictionary, Unity skips the affected entries and logs one console warning.
GetHashCodeEqualsEdit a dictionary in the Inspector
When you select a GameObject or an asset that contains a serialized dictionary, the Inspector renders the dictionary as a two-column list with the keys on the left and the values on the right.

The Inspector displays a dictionary field as a two-column list with the keys on the left and the values on the right.
The Inspector provides the following features:
- Add or remove an entry with the + and - buttons at the bottom of the list.
- Change the width of columns. The width persists per property path and per Inspector window.
- Right-click the column header to change the layout. Refer to Customize the dictionary display.
- Right-click the column header and select Reset Layout to restore the default layout, column split, and sort direction.
- Toggle the sort direction by clicking the Key column header.
- Right-click the column header and select Show Serialized Order (Global) to display entries in their serialized order instead of sorted by key. This setting applies to every dictionary and persists for the current Editor session. It's useful for debugging prefab overrides. Refer to Dictionaries in prefabs.
Dictionary fields don't support multi-object editing. When you select more than one GameObject or asset, the Inspector displays a help box in place of the dictionary editor.
Sort order in the Inspector
The Inspector sorts entries by key for display only. Sorting doesn't change the serialized order, which always reflects the order in which entries were added. Click the Key column header to toggle between ascending and descending order.
The Inspector reads each key directly from the serialized data and compares fields based on their property type. It doesn't call the comparison interface or its method on the key type, so you don't need to implement them for sorting in the Inspector.
IComparable<T>CompareToThe following table describes the sort behavior for each supported key type:
Key type | Sort behavior |
|---|---|
| Numeric order. |
| Numeric order. |
| Case-insensitive natural order: digit runs are compared as numbers, so |
| |
| Enum types | Sorted by enum value index, which matches the order in which you declared the enum members. |
References to | Sorted by internal entity identifier. |
| Structs and classes | Sorted field by field, in declaration order. Refer to Complex key sort order. |
Complex key sort order
When a dictionary key is a struct or serializable class, the Inspector compares entries one field at a time, in the order the fields are declared in your script. It compares the first field of each key. If those values are equal, it moves to the second field, and so on. To change the sort priority, reorder the field declarations in your class.
Only fields visible in the Inspector contribute to the comparison. Fields marked are skipped. The comparison recurses into nested structs and classes up to eight levels deep. Beyond that, remaining nested fields are treated as equal and Unity logs a one-time console warning.
[HideInInspector]When sort order updates
The Inspector re-sorts the displayed entries in the following situations:
- When you add or remove an entry.
- When a key field changes, after you commit the edit (for example, by leaving the field or pressing Enter).
- When external code modifies the serialized property.
While you're actively typing in a key field or dragging a slider, the Inspector defers the re-sort to avoid moving the row out from under you. Duplicate-key markers update in real time so you still see immediate feedback. When you complete the edit, the Inspector re-sorts and your current selection is preserved across the new order.
Customize the dictionary display
Apply the attribute to a dictionary field to set the column layout, the column labels, and the initial column split:
[DictionaryDisplay]using System.Collections.Generic;using UnityEngine;public class LootTable : MonoBehaviour{ [SerializeField] [DictionaryDisplay(keyLabel = "Item", valueLabel = "Drop chance", keyColumnFraction = 0.6f)] private Dictionary<string, float> drops = new Dictionary<string, float>();}
[DictionaryDisplay]- and
keyLabelset the labels for the key and value columns. If you leave one empty, Unity uses a default label (Key or Value).valueLabel - sets the fraction of the available width assigned to the key column. Valid values are between
keyColumnFractionand0.01. The default value is0.99.0.5 - sets the column layout. For more information, refer to Choose a layout.
layout
The parameters set only the initial presentation. If you change the presentation in the Inspector (for example, by dragging the column divider or changing the layout from the header context menu), Unity saves your choice and ignores the initial parameters on later draws. To return to the values set by the attribute, right-click the column header and select Reset Layout.
Choose a layout
To determine how the Inspector arranges keys and values, set the parameter to one of the following values:
layoutDictionaryLayoutLayout | Description |
|---|---|
| Shows keys and values side by side in two resizable columns. This is the default value. |
| Stacks each value under its key in a single column, with every value shown inline. |
| Stacks each value under its key in a single column, with every value behind a collapsible foldout. |
You can also change the layout from the column header's context menu, which overrides the layout set by the attribute.
Customize a dictionary by type
The attribute is a field attribute, so it configures only the single field you attach it to. Apply as an assembly-level attribute instead when you want to:
[DictionaryDisplay][DictionaryDisplayForType]- Configure a dictionary that has no field to decorate, such as the inner dictionary of a , which is a value rather than a field.
Dictionary<int, Dictionary<string, SkillLevel>> - Apply one consistent presentation to every field of the same dictionary type from a single declaration, instead of repeating on each field.
[DictionaryDisplay]
Name the exact dictionary type with . The attribute applies to every dictionary of that exact type, wherever it appears:
typeofusing System.Collections.Generic;using UnityEngine;// One declaration configures every Dictionary<string, SkillLevel> in the assembly: the nested// dictionary in Character and the field in AbilityBook, without repeating [DictionaryDisplay].// This assembly defines SkillLevel, which the attribute requires.[assembly: DictionaryDisplayForType(typeof(Dictionary<string, SkillLevel>), layout = DictionaryLayout.OneColumnWithValueVisible, keyLabel = "Skill", valueLabel = "Level")][System.Serializable]public struct SkillLevel{ public int rank; public float bonus;}public class Character : MonoBehaviour{ // Nested inner dictionary: a value, so it has no field to decorate. [SerializeField] private Dictionary<int, Dictionary<string, SkillLevel>> skillsPerTier = new();}public class AbilityBook : MonoBehaviour{ // A direct field of the same type, styled by the same declaration. [SerializeField] private Dictionary<string, SkillLevel> learnedSkills = new();}
[DictionaryDisplayForType][DictionaryDisplay]typeof- It must be a fully specified , such as
Dictionary<TKey, TValue>. Unity ignores a target that isn't a fully specified dictionary type. The analyzer reports UAC1021.Dictionary<string, SkillLevel> - It must use a type defined in the same assembly as the attribute: its key type, its value type, or a type nested inside either. For example, an assembly that defines can target
SkillLevel,Dictionary<string, SkillLevel>, orDictionary<int, SkillLevel[]>. This prevents a rule in one assembly from changing a dictionary built only from types it doesn't define, such asDictionary<int, List<SkillLevel>>. If the target uses no type from the attribute's assembly, Unity ignores the rule and logs a warning in the console. The analyzer reports UAC1022.Dictionary<int, int>
When a dictionary is nested as the value of another dictionary, the Inspector uses Dictionary as the label for the inner dictionary's foldout, because a dictionary value has no field name.
Resolution order
When more than one source can set a dictionary's presentation, Unity uses the first source that applies, from highest precedence to lowest:
- The user's own in-editor choices: the layout from the header context menu and the column width from dragging the divider. Unity persists these choices per property path until the user selects Reset Layout.
- A field-level on the dictionary field sets the layout, labels, and width.
[DictionaryDisplay] - An assembly-level on the exact
[DictionaryDisplayForType]sets the layout, labels, and width.Dictionary<TKey, TValue> - The built-in defaults: layout, Key and Value labels, and a 0.5 key-column fraction.
TwoColumns
Duplicate keys
A dictionary can contain only one value for each key at runtime, but the Inspector lets you create duplicate keys temporarily so you can resolve them incrementally. Unity marks each duplicate row with an icon and a tooltip, and preserves the duplicate entries in the asset until you correct or remove them. Duplicate entries are tracked per host object only in the Editor; the Player runtime always enforces unique keys.
When Unity loads a scene, prefab, or asset that contains a serialized dictionary with duplicate keys, or when you instantiate an object that contains such a dictionary, the Editor writes a warning in the console. Unity adds only the first occurrence of each duplicate key to the runtime dictionary.
If you need to read the duplicate indices from a custom Inspector or other tooling, use and read its array.
SerializedProperty.GetDictionaryIgnoredEntriesduplicateEntryIndicesNull keys
A dictionary can't contain a null key at runtime, but the Inspector keeps a row whose key is null so you can assign a valid key to it. A row has a null key when you add an entry with the + button and haven't set the key yet, or when a key is unassigned or refers to an object that no longer exists. Unity marks each null-key row with an icon and a tooltip, and preserves the row in the serialized data so you don't lose it or its value.
UnityEngine.ObjectWhen Unity loads a scene, prefab, or asset that contains a serialized dictionary with null-key rows, or when you instantiate an object that contains such a dictionary, the Editor writes a warning in the console and excludes those rows from the runtime dictionary. Unity keeps each null-key row as a separate placeholder rather than merging rows that share a null key, so no value is lost.
If a dictionary contains both duplicate keys and null keys, Unity reports them in a single console warning rather than one warning for each problem.
If you need to read the null-key indices from a custom Inspector or other tooling, use and read its array.
SerializedProperty.GetDictionaryIgnoredEntriesnullKeyEntryIndicesDictionaries in prefabs
You can override individual entries of a serialized dictionary on a prefab instance. The Inspector indicates each overridden key or value the same way it indicates other property overrides, and you can apply or revert each overridden key or value independently.
Unity records dictionary overrides using the serialized position of the entry, the same way it records overrides on array and list fields.
Dictionaries add extra complexity for prefab overrides. The Inspector displays entries in sorted order rather than in the order they were added or stored, so the row position you see doesn't correspond to the entry's storage position. After you delete or add an entry on the prefab asset, review the instance overrides to confirm they still apply to the entries you intended.
To make overrides easier to reason about, right-click the column header and select Show Serialized Order (Global). The Inspector then displays entries in their serialized order, so each row's position matches the storage index that Unity records the override against.
For the logic behind this behavior and an example, refer to Overrides on arrays, lists, and dictionaries.
Limitations
- Multi-object editing isn't supported. The Inspector shows a help box when more than one target is selected.
- Since Unity records dictionary overrides using the serialized array index, editing a dictionary on a prefab asset can leave existing instance overrides applied to a different entry. For more information, refer to Overrides on arrays, lists, and dictionaries.
- The Inspector sort order doesn't change the serialized order, which always reflects insertion order.
- Search and filter aren't available in the Inspector for dictionary entries.