介绍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<>>
相关推荐
天人合一peng1 小时前
Unity 中 Text-TextMeshPro的获取与赋值
unity·游戏引擎
天人合一peng20 小时前
Unity中button 和toggle监听事件函数有无参数
前端·unity·游戏引擎
_乐无21 小时前
Unity加载gly 点云 高斯泼溅渲染
unity
坚定信念,勇往无前21 小时前
unity发布BuildWebGL.wasm 加载过慢
unity·wasm
avi91111 天前
Unity Data Excel读取方法+踩坑记;和WPS Excel的一些命令
unity·游戏引擎·excel·wps·data
郁闷的网纹蟒1 天前
虚幻5---第12部分---蒙太奇
开发语言·c++·ue5·游戏引擎·虚幻
天人合一peng1 天前
Unity 中Canvas 或image打勾时不显示
unity
淡海水2 天前
【节点】[Houndstooth节点]原理解析与实际应用
unity·游戏引擎·shadergraph·图形·houndstooth
微:xsooop3 天前
iOS上架被拒4.3(a) 10次到过审历程
flutter·unity·ios·uniapp
DoomGT3 天前
Physics Simulation - Hit Event的触发机制
ue5·游戏引擎·虚幻·虚幻引擎·unreal engine