介绍Unity中的Dictionary

在 Unity(C#)中,Dictionary 是一个非常常用的数据结构,它提供 键值对(Key-Value Pair) 的存储方式。类似于 Python 的 dict 或 JavaScript 的对象(Object),但它是强类型的、使用泛型。


基础概念:什么是 Dictionary?

C# 中的 Dictionary<TKey, TValue> 是一个泛型集合,你可以根据某个键(Key)快速查找、添加或删除对应的值(Value)。

适合用在什么时候?

  • 需要快速查找(复杂度约为 O(1))

  • 想通过"某个唯一标识"存储对应数据,如:

    • ID → 玩家对象
    • 名字 → 数值
    • 类型 → Prefab

常用语法

1. 声明 Dictionary

csharp 复制代码
Dictionary<string, int> scoreDict = new Dictionary<string, int>();

2. 添加数据

csharp 复制代码
scoreDict.Add("Player1", 100);

3. 读取数据

csharp 复制代码
int score = scoreDict["Player1"];

4. 修改数据

csharp 复制代码
scoreDict["Player1"] = 200;

5. 判断是否包含某个键

csharp 复制代码
if (scoreDict.ContainsKey("Player1")) {
    Debug.Log("存在 Player1");
}

6. 遍历 Dictionary

csharp 复制代码
foreach (KeyValuePair<string, int> entry in scoreDict)
{
    Debug.Log(entry.Key + ": " + entry.Value);
}

7. 删除键值对

csharp 复制代码
scoreDict.Remove("Player1");

Unity 实战场景示例

示例:根据字符串名字加载预制体

csharp 复制代码
public class PrefabManager : MonoBehaviour
{
    public GameObject redGem;
    public GameObject blueGem;

    private Dictionary<string, GameObject> prefabDict;

    void Start()
    {
        prefabDict = new Dictionary<string, GameObject>();
        prefabDict.Add("Red", redGem);
        prefabDict.Add("Blue", blueGem);

        GameObject gem = Instantiate(prefabDict["Red"], new Vector2(0, 0, 0), Quaternion.identity);
    }
}

⚠️ 注意事项

  1. 键(Key)不能重复,否则会抛异常。
  2. 如果你不确定键是否存在,请用 .ContainsKey().TryGetValue()
  3. Dictionary 是无序的。如果你需要有序,可以用 SortedDictionaryList<KeyValuePair<>>
相关推荐
叶帆17 天前
【YFIOs】用C#开发硬件之设备上云
开发语言·unity·c#
久数君17 天前
AI三维建模工具“造形家”:地理场景三维化的高效解决方案
unity·glb·ai算法·ai三维建模工具·地图框选·造形家·城市建筑模型
会思考的猴子17 天前
Unity VFX 属性 Postion 和 TargetPostion
unity
hai31524754317 天前
九章编程法 · 猜数字游戏 (GW-BASIC 重构版) *
人工智能·microsoft·游戏引擎·游戏程序
心前阳光17 天前
Unity资源导入之自动化资源导入
unity·自动化·游戏引擎
心前阳光18 天前
Unity之2021.3.45f2c1发布安卓程序遇到的问题
android·unity·游戏引擎
纪纯18 天前
PicoVR Unity Integration SDK 3.4 常用交互API
unity·游戏引擎·vr·pico
龙智DevSecOps解决方案18 天前
3A 游戏优化技术栈:如何打通引擎级分析工具与 DevOps 持续集成管线?
unity·性能优化·游戏开发·技术美术·perforce·unrealengine
葛兰岱尔18 天前
从 SolidWorks 到 Three.js,从 Inventor 到 Unity——制造业CAD模型“几何-语义一体化“转换,不再是天方夜谭!
开发语言·javascript·unity
鼎艺创新科技18 天前
三维电子沙盘中OSGB倾斜摄影数据的加载与渲染
游戏引擎·cocos2d