######写了一个关于随机生成怪兽的脚本,结果运行报错
public GameObject[] monster;
public Transform[] monsterpos;
private int index;
// Use this for initialization
void Start () {
InvokeRepeating("MonsterCreat", 5, 5);
}
// Update is called once per frame
void Update () {
int index = Random.Range(0, 3);
}
void MonsterCreat()
{
Instantiate(monster[Random.Range(0, 3)], monsterpos[index]);
}
IndexOutOfRangeException: Array index is out of range.
MonsterCreats.MonsterCreat () (at Assets/Jiaoben/MonsterCreats.cs:21)
出现了这个报错
你的Update函数中,重新申请了index变量来接收随机数是不对的,应该是给类的成员变量index赋值。
修改如下:
void Update () {
index = Random.Range(0, 3); // int index = Random.Range(0, 3); 给成员变量index赋值
}
另外,最好在构造函数或者其它初始化函数中,把成员变量index初始化一下 index = 0;
索引越界,检查一下你的数组到底有多少个元素,产生的随机数可能大于等于最大下标值了