c# - 将 GameObjects 存储在自定义类列表中的数组中 - 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 Game 并编写 Obstacle Generator 脚本。我最初从 List> 开始,但发现创建自定义类会更好。所以我创建了自定义类 ObstacleSpawned ,其中包含一个 GameObject[] ,它应该包含该类型障碍物的实例,但我有一个空引用异常
obsItem.spawnedObstacles.Add (obstacle);
当我试图找出问题所在时,它是 spawnedObstacles 因为它也给出了空引用异常
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);
}
}
}
预期结果应采用包含 ObstacleSpawned 类的列表的形式,每个类都包含多个实例。我正在尝试这样做,但它给了我空引用异常。
解决方案
您正在设置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);
}
}
推荐阅读
- ocaml - 使用尾递归 OCaml 的俄罗斯农民求幂
- java - 如何访问嵌套在 Java 中 Apache Camel 的 ${body} 中的地图列表
- bash - 如何排除`.git`然后备份和恢复文件夹和文件的所有者和权限?
- excel - excel IE运行时中的VBA和windows安全警告弹出
- qt - 使用 QProcess 启动应用程序和脚本
- javascript - 使用 this.closest 删除添加到 HTML 表中的动态列
- c# - 为什么视图状态、会话和应用程序状态被认为对 Web 应用程序不利?
- python - 如何格式化具有宽度和文字的字符串?
- git - 如何注入中间分支?
- replace - 在特定情况下替换特定单元格的文本