在 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);
}
}
⚠️ 注意事项
- 键(Key)不能重复,否则会抛异常。
- 如果你不确定键是否存在,请用
.ContainsKey()
或.TryGetValue()
。 Dictionary
是无序的。如果你需要有序,可以用SortedDictionary
或List<KeyValuePair<>>
。