介绍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

Dictionary<string, int> scoreDict = new Dictionary<string, int>();

2. 添加数据

scoreDict.Add("Player1", 100);

3. 读取数据

int score = scoreDict["Player1"];

4. 修改数据

scoreDict["Player1"] = 200;

5. 判断是否包含某个键

if (scoreDict.ContainsKey("Player1")) {
    Debug.Log("存在 Player1");
}

6. 遍历 Dictionary

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

7. 删除键值对

scoreDict.Remove("Player1");

Unity 实战场景示例

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

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<>>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值