Appearance
数组
数组是什么
数组就是“一排固定数量的格子”。每个格子有编号,编号叫 索引 index。C# 数组索引从 0 开始。
c
int[] scores = { 90, 75, 88 };
Debug.Log(scores[0]); // 90
Debug.Log(scores[1]); // 75
Debug.Log(scores[2]); // 88scores.Length 是数组长度。 长度是 3,有效下标就是 0、1、2。 写 scores[3] 会越界。
声明、创建、初始化
c
int[] numbers; // 声明,还没有真正数组
numbers = new int[3]; // 创建 3 个 int 格子
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
int[] ids = { 1, 2, 3 }; // 创建并初始化默认值要记住: int 默认是 0,float 默认是 0,bool 默认是 false,引用类型默认是 null。
for 和 foreach
需要下标,用 for:
c
for (int i = 0; i < scores.Length; i++)
{
Debug.Log(scores[i]);
}只想逐个读取,用 foreach:
c
foreach (int score in scores)
{
Debug.Log(score);
}Unity 里最常见用法
c
using UnityEngine;
public class EnemySpawner : MonoBehaviour
{
[SerializeField] private GameObject[] enemyPrefabs;
[SerializeField] private Transform[] spawnPoints;
public void Spawn(int enemyIndex, int pointIndex)
{
GameObject prefab = enemyPrefabs[enemyIndex];
Transform point = spawnPoints[pointIndex];
Instantiate(prefab, point.position, point.rotation);
}
}这里 enemyPrefabs 是敌人预制体数组,spawnPoints 是出生点数组。你可以在 Inspector 里拖多个对象进去。
数组 vs List
数组适合:数量固定,比如 3 个难度、10 个背包槽、固定巡逻点。 List<T> 适合:数量经常变化,比如动态任务、敌人列表、好友列表。
c
int[] slots = new int[10]; // 固定 10 个
List<int> items = new(); // 可以 Add / Remove三个常见坑
- 下标越界:
i <= array.Length是错的,通常写i < array.Length。 - 引用数组元素可能是
null:new GameObject[3]只是 3 个空格子,不会自动生成对象。 - 数组长度不能变:想频繁增删,就用
List<T>。
参考链接Microsoft C# ArraysMicrosoft System.ArrayMicrosoft Multidimensional arraysMicrosoft Jagged arraysUnity Script Serialization Rules