首页 > 解决方案 > 将 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 类的列表的形式,每个类都包含多个实例。我正在尝试这样做,但它给了我空引用异常。

标签: c#listunity3d

解决方案


您正在设置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);
    }
}

推荐阅读