介绍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<>>
相关推荐
KhalilRuan6 小时前
Unity性能优化
unity·性能优化·游戏引擎
ellis19707 小时前
u3d IMGUI[二] 编辑器扩展
unity
五仁烧饼18 小时前
Unity性能优化系列内存篇 - 移动端内存优化
unity·性能优化·游戏引擎
WiChP2 天前
【V0.1B15】从零开始的2D游戏引擎开发之路
游戏引擎
zhchyun20084 天前
# 【Unity UI 进阶】仿 Element UI 打造企业级 Unity UI 组件库(06)
ui·unity·游戏引擎
Behaviour4 天前
Unity游戏HybridCLR 热更新接入实战
游戏·unity·游戏引擎
LONGZETECH4 天前
新能源汽车动力电池实训教学痛点与虚拟仿真技术解决方案
c语言·3d·unity·架构·汽车·汽车教学软件
王维志4 天前
UiSplineRenderer
unity·游戏引擎
k4m7v2pz5 天前
Godot 4 仿 agar.io:相机缩放被 max_zoom 卡死,窗口越大球越小的根因与修复
游戏引擎·godot·相机·缩放·clamp·camera2d
FairGuard手游加固5 天前
iOS 游戏加固技术解析:代码混淆、资源加密、内存保护与重签名检测
安全·游戏·macos·unity·ios·objective-c