【发布时间】:2015-04-08 16:43:03
【问题描述】:
我创建了预制件,并以 0, 1 ... 9 命名。
我想用rigidbody 和collision 创建一个数字。但是我收到以下异常:
IndexOutOfRangeException:数组索引超出范围。 (包装器 stelemref) 对象:stelemref (object,intptr,object) Spawn_Score.Start () (在 Assets/Spawn_Score.cs:17)
代码:
using UnityEngine;
using System.Collections;
public class Spawn_Score : MonoBehaviour {
private Vector3 startPosition;
private Quaternion startRotation;
public GameObject[] number_object;
public int position;
public int count;
// Use this for initialization
void Start () {
for (int i = 0; i < 9; i++) {
number_object [i] = (GameObject)Resources.Load (i.ToString());
}
GenerateScore ();
}
// Update is called once per frame
void Update () {
}
void GenerateScore() {
startRotation = transform.rotation;
count = PlayerPrefs.GetInt ("PlayerScore").ToString ().Length;
for (int i = 1; i < count; i++) {
//int number;
startPosition = new Vector3 (2f*i, 5.6f, 0);
//number = (int)PlayerPrefs.GetInt("PlayerScore").ToString()[i];
Instantiate (number_object[1], startPosition, startRotation);
}
}
}
【问题讨论】:
-
您还没有向我们展示
number_object的初始化位置。 (您已经向我们展示了填充数组的位置,但没有展示您实际初始化变量的位置。) -
这就是我所拥有的一切。 number_object 不是在页面顶部初始化的吗?如果我是对的。
-
不,它在代码的早期声明,但它的默认值是
null。所以必须初始化它,否则你会得到一个NullReferenceException。 Unity 的某些神奇部分可能会自动对其进行初始化,但我不知道它如何知道数组的大小。 -
嗯,10 是我命名为 '0' -> '9' 的预制件数量,所以我不明白我不能简单地手动放入它们,因为这些数量不会改变。 For 循环应该在开始 void 时执行此操作。
-
我认为你没有抓住重点。除非变量已使用足够大的数组进行初始化,否则您希望该循环如何工作?