You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity中Dictionary能否序列化?如何在Inspector中查看?

在Unity Inspector中查看Dictionary的方案

Unity默认不支持直接在Inspector面板显示Dictionary类型,因为它本身不可序列化。下面是可行的解决思路,以及替代的数据结构推荐:

一、自定义Inspector显示Dictionary

通过序列化键值对列表+编辑器扩展的方式,实现Inspector可视化编辑:

  1. 定义可序列化的键值对类
using UnityEngine;

[Serializable]
public class SerializableKeyValuePair<TKey, TValue>
{
    public TKey Key;
    public TValue Value;
}
  1. 在业务脚本中维护列表与Dictionary的同步
using System.Collections.Generic;
using UnityEngine;

public class YourGameScript : MonoBehaviour
{
    // 在Inspector中显示的键值对列表
    public List<SerializableKeyValuePair<string, int>> keyValueList = new List<SerializableKeyValuePair<string, int>>();
    // 实际业务逻辑使用的Dictionary
    private Dictionary<string, int> dataDictionary = new Dictionary<string, int>();

    // 编辑模式下自动同步列表到Dictionary
    private void OnValidate()
    {
        dataDictionary.Clear();
        foreach (var pair in keyValueList)
        {
            // 避免重复键报错
            if (!dataDictionary.ContainsKey(pair.Key))
            {
                dataDictionary.Add(pair.Key, pair.Value);
            }
        }
    }
}
  1. (可选)编写自定义Editor脚本增强交互
    如果需要更友好的编辑体验(比如一键添加/删除键值对),在Editor文件夹下创建自定义编辑器脚本:
using UnityEditor;
using UnityEngine;

[CustomEditor(typeof(YourGameScript))]
public class DictionaryEditor : Editor
{
    public override void OnInspectorGUI()
    {
        base.OnInspectorGUI();
        YourGameScript targetScript = (YourGameScript)target;

        if (GUILayout.Button("添加键值对"))
        {
            targetScript.keyValueList.Add(new SerializableKeyValuePair<string, int>());
        }

        if (GUILayout.Button("同步到Dictionary"))
        {
            targetScript.OnValidate();
        }
    }
}

二、Unity官方推荐的替代数据结构

如果不想自己写编辑器逻辑,可以直接使用Unity提供的可序列化替代方案:

  • SerializedDictionary:Unity Collections包中的SerializedDictionary支持直接在Inspector显示,内置序列化和编辑逻辑。在Package Manager中安装Unity Collections包后即可使用:
using UnityEngine;
using Unity.Collections;

public class ExampleScript : MonoBehaviour
{
    public SerializedDictionary<string, float> serializedDict;
}
  • ScriptableObject存储结构化数据:如果数据需要跨场景复用或批量编辑,可将键值对数据存在ScriptableObject中,配合自定义Editor实现类似Dictionary的管理,适合配置类数据。

内容的提问来源于stack exchange,提问作者김현준

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 02:01:14