有人知道为什么这会给游戏对象数组的索引带来错误吗?
public GameObject[] Prefab;
public GameObject[] CopyPrefab;
for (int i = 0; i < 10; i++)
{
CopyPrefab[i] = Instantiate(Prefab[i]) as GameObject;
}
错误:IndexOutOfRangeExCeption: Index was outside the bounds of the array.
我尝试了CopyPrefab[i-1] = Instantiate(Prefab[i-1]) as GameObject;
和CopyPrefab[i] = Instantiate(Prefab[0]) as GameObject;
。我不明白我在做什么错
答案 0 :(得分:3)
您如何知道GameObject []中对象的确切数量?不要将循环结束条件硬编码为i <10。相反,您应该使用foreach循环进行循环或使用Array的Length属性。
答案 1 :(得分:0)
public GameObject[] Prefab;
public GameObject[] CopyPrefab;
CopyPrefab = new GameObject[Prefab.Length];
for (int i = 0; i < Prefab.Length; i++)
{
CopyPrefab[i] = Instantiate(Prefab[i]) as GameObject;
}
首先,确保两个数组长度相同,如果CopyPrefab.Length = 10, 您只能使用CopyPrefab [0 ... 9],不能使用CopyPrefab [-1]或CopyPrefab [10] ...“超出范围”