[英]Storing GameObjects in arrays in list of custom classes - Unity3D and 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類的列表的形式,每個類均包含實例數量。 我正在嘗試這樣做,但是它給了我null引用異常。
您正在設置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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.