Appearance
List
List 是什么
List<T> 是“长度可以变化的同类型列表”。 数组 int[] 长度固定,而 List<int> 可以 Add、Remove、Clear。
c
using System.Collections.Generic;
List<string> items = new List<string>();
items.Add("Sword");
items.Add("Potion");
items.Add("Key");
Debug.Log(items[0]); // Sword
Debug.Log(items.Count); // 3T 是什么意思
List<T> 里的 T 是类型占位符。
List<int> scores; // 只能放 int
List<string> names; // 只能放 string
List<GameObject> prefabs; // 只能放 GameObjectCount 和 Capacity
Count:当前真的有几个元素。 Capacity:内部预留了多少空间。
你访问列表时,只看 Count:
c
for (int i = 0; i < items.Count; i++)
{
Debug.Log(items[i]);
}不要把 Capacity 当成可访问数量。Capacity 是内部容量,不代表里面有元素。
常用操作
c
items.Add("Bow"); // 添加到末尾
items.Insert(0, "Axe"); // 插入到指定位置
items.Remove("Key"); // 按值删除
items.RemoveAt(1); // 按下标删除
items.Clear(); // 清空
bool hasSword = items.Contains("Sword");遍历时怎么选
只读取,用 foreach:
c
foreach (string item in items)
{
Debug.Log(item);
}需要下标,用 for:
c
for (int i = 0; i < items.Count; i++)
{
Debug.Log(items[i]);
}边遍历边删除,倒着删:
c
for (int i = items.Count - 1; i >= 0; i--)
{
if (items[i] == "Potion")
{
items.RemoveAt(i);
}
}Unity 里常见用法
c
using System.Collections.Generic;
using UnityEngine;
public class EnemyManager : MonoBehaviour
{
private List<Enemy> enemies = new List<Enemy>();
public void AddEnemy(Enemy enemy)
{
enemies.Add(enemy);
}
public void RemoveDeadEnemies()
{
for (int i = enemies.Count - 1; i >= 0; i--)
{
if (enemies[i] == null || enemies[i].IsDead)
{
enemies.RemoveAt(i);
}
}
}
}数组 vs List
数量固定,用数组:出生点、固定 UI 槽位、固定技能栏。 数量变化,用 List<T>:敌人、背包、任务、掉落物、弹幕对象。
常见坑
foreach 里不要修改当前列表。 RemoveAt 会让后面的元素前移。 Find、Contains 是线性查找,大列表频繁查会慢。 Update 里频繁 new List()、ToArray()、FindAll() 容易产生 GC。
参考链接Microsoft ListMicrosoft CollectionsMicrosoft List.CountMicrosoft List.CapacityUnity Script Serialization Rules