unity NullReferenceException 当对象刚被赋值时

Unity NullReferenceException when object has just been assigned

我有一个正在实例化的游戏对象:

var face = Instantiate(waveConfigs[waveNumber].getFacePrefab(), waypoint.position, Quaternion.identity, FindObjectOfType<Canvas>().transform);

Debug.Log(face, this);
faces.Add(face);

faces 在上面这样声明:

List<GameObject> faces;

对象被实例化,DebugLog如下:

Smile(Clone) (UnityEngine.GameObject)
UnityEngine.Debug:Log(Object)
FaceSpawner:SpawnFaces(Int32) (at Assets/Scripts/FaceSpawner.cs:30)
FaceSpawner:Start() (at Assets/Scripts/FaceSpawner.cs:16)

(哪个是Debug.Log(face,this);)

紧接着,当我调用 faces.Add() 时:

NullReferenceException: Object reference not set to an instance of an object
FaceSpawner.SpawnFaces (System.Int32 waveNumber) (at Assets/Scripts/FaceSpawner.cs:31)
FaceSpawner.Start () (at Assets/Scripts/FaceSpawner.cs:16)

我不明白,我确实 只是 分配了这个变量,它起作用了,它出现在 canvas 上,我可以将它从调试日志中注销,然后当我尝试将它添加到列表时,我得到一个 NullReference。这是怎么回事?

您的 faces 容器是否也被初始化过 List<GameObject> faces = new List<GameObject>()

问题是您正在尝试 Add 尚未创建的容器,即尚未为其分配内存且尚未调用其构造函数的容器。所以基本上你试图在不存在的对象上调用函数 Add