【问题标题】:Storing GameObjects in arrays in list of custom classes - Unity3D and C#将 GameObjects 存储在自定义类列表中的数组中 - Unity3D 和 C#
【发布时间】:2018-12-25 11:23:59
【问题描述】:

我的想法是创建一个包含障碍物预制件的自定义类列表,存储每种障碍物类型的大约 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 游戏并编写 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# list unity3d


    【解决方案1】:

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

    【讨论】:

    • 注释掉的Add() 行不是很有用。
    • 当然,这是 OP 提供的代码。我只是修复了这个错误,OP希望如何使用它取决于他们。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-09
    • 2013-07-30
    • 2019-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-16
    相关资源
    最近更新 更多