IndexOutOfRangeException: Array index is out of range怎样解决

using UnityEngine;
using System.Collections;
public class random : MonoBehaviour {
GameObject Ben;
public GameObject[] Balls;
float t1=0.0f;
float t2=3.0f;
// Use this for initialization
void Start () {
Ben=GameObject.Find("Sphere");
}

// Update is called once per frame
void Update () {
t1+=Time.deltaTime;
if(t1>=t2)
{
Ben.transform.position=new Vector3((Random.value*14-7.0f),Ben.transform.position.y,Ben.transform.position.z);
Instantiate(Balls[Mathf.FloorToInt(Random.value*3)],Ben.transform.position,Ben.transform.rotation);
t1=0.0f;
}

}
}
这个代码是随机生成对象的代码,可是在运行时总是提醒 Instantiate(Balls[Mathf.FloorToInt(Random.value*3)],Ben.transform.position,Ben.transform.rotation);本行有 Instantiate(Balls[Mathf.FloorToInt(Random.value*3)],Ben.transform.position,Ben.transform.rotation);代码。怎样解决呢。

具体解决方法如下:

1、首先可以看到在运行程序的时候,出现list index out of range错误,如下图所示:

2、需要知道list index out of range错误出现的原因主要有两个,一个可能是下标超出范围,一个可能是list是空的,没有一个元素,如下图所示:

3、知道原因之后,我们来看一下报错的代码,可以看到这个错误的原因是定义了一个空list,如下图所示:

4、修改代码,定义一个固定长度的list,并初始都赋值为0,如下图所示:

5、再次运行程序,可以看到已经解决了list index out of range错误,主要看代码是下标越界错误,还是空列表错误,然后对症解决,如下图所示:

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2017-06-14
这个异常意思是说,数组索引超越的边界。 就像只有4个项的数组中,你却要找他的第5项数据。
问题应该出在Balls[Mathf.FloorToInt(Random.value*3)]中,Mathf.FloorToInt(Random.value*3)算出来的数字是大于balls这个数据的长度的。追问

可是balls是一个实例化啊。。里面是4个球类对象来着……那要怎么改呢~~~

本回答被网友采纳
第2个回答  2014-10-19
你在声明Balls的时候只是声明它是一个GameObject类的数组,并没有声明数组的长度,所以你之后对这个数组中任何数据的操作都会被认定为越界。

解决方法是对这个数组的长度进行赋值:
int i=XXX;
Balls = new Object[i];
相似回答