Skip to content

集合与数据结构

unity-csharp-collections-data-structures

核心理解

集合就是“装很多数据的容器”。数据结构就是“这个容器怎么组织数据”。

你不要先背名字,先问需求:

固定数量,用 Array 数组。 经常增删,用 List<T>。 根据 ID / 名字快速查值,用 Dictionary<TKey, TValue>。 只关心有没有,并且不想重复,用 HashSet<T>。 先进先出,用 Queue<T>。 后进先出,用 Stack<T>

最常用写法

c
int[] scores = new int[3];

List<string> items = new List<string>();
items.Add("Potion");

Dictionary<string, int> bag = new Dictionary<string, int>();
bag["coin"] = 100;

HashSet<int> unlockedLevels = new HashSet<int>();
unlockedLevels.Add(1);

Queue<string> tasks = new Queue<string>();
tasks.Enqueue("SpawnEnemy");

Stack<string> history = new Stack<string>();
history.Push("MenuPage");

Unity 里怎么用

List<T> 是你最常用的集合,比如敌人列表、出生点列表、背包格子:

c
[SerializeField] private List<Transform> spawnPoints;
private List<Enemy> enemies = new List<Enemy>();

Dictionary 适合做“ID 到数据”的映射:

c
private Dictionary<string, int> itemCounts = new();

itemCounts["coin"] = 100;

if (itemCounts.TryGetValue("coin", out int count))
{
    Debug.Log(count);
}

HashSet 适合做状态记录:

c
private HashSet<int> unlockedLevels = new();

if (!unlockedLevels.Contains(3))
{
    unlockedLevels.Add(3);
}

Unity 注意点

运行时代码里,这些集合都能正常用。 Inspector 配置里,数组和 List<T> 最稳定、最常见。 Dictionary 的 Inspector/序列化支持要看 Unity 版本;较新的 Unity 文档有 Dictionary 序列化规则,旧项目里经常用 List<Pair> 或自定义序列化替代。

参考链接

文章评价

读完这篇,留下你的看法

暂无审核通过的评价。

登录账号后才能评价。

本站访客数0总站访问量0本页访问量0