C# 从阵列实例化和销毁游戏对象
我想将一个预置的多个实例实例化到一个数组中,每个实例都有自己的索引号,但我一直得到错误代码“object reference not set to a instance of a object.我如何才能消除此错误,如何才能销毁单个对象或检索数组中每个游戏对象的属性?”C# 从阵列实例化和销毁游戏对象,c#,arrays,unity3d,C#,Arrays,Unity3d,我想将一个预置的多个实例实例化到一个数组中,每个实例都有自己的索引号,但我一直得到错误代码“object reference not set to a instance of a object.我如何才能消除此错误,如何才能销毁单个对象或检索数组中每个游戏对象的属性?” using UnityEngine; using System.Collections; public class SpawnEnemy : MonoBehaviour { private GameObject[] enemy
using UnityEngine;
using System.Collections;
public class SpawnEnemy : MonoBehaviour {
private GameObject[] enemy;
public GameObject enemyPrefab;
// Use this for initialization
void Start () {
enemy[1] = (GameObject)Instantiate (enemyPrefab, new Vector3 (-119, 52, 483), transform.rotation);
}
// Update is called once per frame
void Update () {
if (Input.GetButtonDown ("Fire2")) {
Destroy (enemy[1]);
}
}
}
在设置
敌方[1]
的值之前,您尚未实例化数组。此外,索引应为0,而不是1,即敌方[0]=
…因为C#数组的索引从0开始
您可以使用下面的方法进行实例化和设置
enemy = new[]
{
(GameObject)Instantiate(enemyPrefab,
new Vector3 (-119, 52, 483), transform.rotation)
};
正如DrUsh提到的,您需要初始化数组,例如:
void Start()
{
// initialize array with a size of 5, all elements are empty
enemy = new GameObject[5];
// now you can work with this array, e.g. like you line:
enemy[1] = (GameObject)Instantiate (enemyPrefab, new Vector3 (-119, 52, 483), transform.rotation);
}
使用数组的缺点是,您将拥有固定数量的元素(在我的示例中为5个)。如果您不知道在同一时间存储到数组中的最大对象的确切数量,则最好使用可动态调整大小的列表。这还需要通过放置敌方=新列表()来初始化
另外,你可能不想访问带有硬编码索引的数组/列表。我不知道这是否只是一个例子,你有一个更好的、自动创建游戏对象索引对的方法