将游戏对象存储在自定义类列表中的数组中-Unity3D和C#



我想到的是创建一个包含障碍物预制的自定义类列表,存储每个障碍物类型的大约5个实例。所以这个列表看起来像这样:

Obstacle Type [0] ------> [0] Instance 1
[1] Instance 2
[2] Instance 3...
Obstacle Type [1] ------> [0] Instance 1
[1] Instance 2
[2] Instance 3...

我目前正在Unity3D中编程3D Runner游戏,并编程障碍生成器脚本。我最初使用List>,但发现创建一个自定义类会更好。因此,我创建了自定义类ObstructureSpawned,其中包括一个GameObject[],它应该包括该类型障碍的实例,但我在中有一个空引用异常

obsItem.spawnedObstacles.Add (obstacle);

当我试图弄清楚问题出在哪里时,是spawnedObstructures,因为它在中也给出了null引用异常

print (obsItem.spawnedObstacles);

我不知道该怎么解决。我甚至不知道代码是否有效。

[Serializable]
public class ObstacleTypes {
public GameObject prefab;
public string name;
}
[Serializable]
public class ObstacleSpawned {
public List<GameObject> spawnedObstacles = new List<GameObject>();
}
public class ObstacleGenerator : MonoBehaviour {
// variables
public ObstacleTypes[] obstacles;
public List<ObstacleSpawned> obstaclesSpawned = new List<ObstacleSpawned> ();
[SerializeField] int numberOfInstances;
void Awake () {
for (int x = 0; x < numberOfInstances; x++) {
ObstacleSpawned obsItem = null;
for (int y = 0; y < obstacles.Length; y++) {
GameObject obstacle = Instantiate (obstacles [y].prefab, transform) as GameObject;
obstacle.name = obstacles [y].name;
obstacle.SetActive (false);
//obsItem.spawnedObstacles.Add (obstacle);
print (obsItem.spawnedObstacles);
}
obstaclesSpawned.Add (obsItem);
}
}
}

预期的结果应该是一个包含ObstructureSpawned类的列表,每个类都包含多个实例。我正在尝试这样做,但它给了我空引用异常。

您正在设置ObstacleSpawned obsItem = null;,然后尝试引用obsItem上的一个属性,这将为您提供NRE。将其更改为ObstacleSpawned obsItem = new ObstacleSpawned();,如下所示:

void Awake () {
for (int x = 0; x < numberOfInstances; x++) {
ObstacleSpawned obsItem = new ObstacleSpawned();
for (int y = 0; y < obstacles.Length; y++) {
GameObject obstacle = Instantiate (obstacles [y].prefab, transform) as GameObject;
obstacle.name = obstacles [y].name;
obstacle.SetActive (false);
//obsItem.spawnedObstacles.Add (obstacle);
print (obsItem.spawnedObstacles);
}
obstaclesSpawned.Add (obsItem);
}
}

最新更新