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错误,主要看代码是下标越界错误,还是空列表错误,然后对症解决,如下图所示:
可是balls是一个实例化啊。。里面是4个球类对象来着……那要怎么改呢~~~
本回答被网友采纳