简体   繁体   English

数组索引超出范围错误

[英]Array index is out of range error

I'm using this code to spawn a random object from an array: 我正在使用以下代码从数组中生成随机对象:

using UnityEngine;
using System.Collections;

public class enemySpawner : MonoBehaviour {

    public GameObject[] enemies; 
    int enemyNo;
    public float maxPos = 6.9f;
    public float delayTimer = 0.75f;
    float timer; 

    void Start () {
        timer = delayTimer;
    }

    void Update () {

        timer -= Time.deltaTime;

        if (timer <= 0) {

            Vector3 enemyPos = new Vector3 (transform.position.x, Random.Range (5.0f, -5.5f), transform.position.z);

            //enemyNo = Random.Range (0,8);    
            enemyNo = Random.Range (0, enemies.Length);

            Instantiate (enemies[enemyNo], enemyPos, transform.rotation);
            timer = delayTimer;
        }
    }
}    

The problem is I want to do the same thing across different scenes. 问题是我想在不同的场景中做同样的事情。 Each scene has a different amount of objects for the array (set in the inspector), so because they're not all the same I'm getting this error: 每个场景的数组对象数量不同(在检查器中设置),因此由于它们不尽相同,因此出现此错误:

IndexOutOfRangeException: Array index is out of range.

Is there any way for me to do this differently? 有什么办法可以让我与众不同吗? Or should I write a new script for each scene? 还是应该为每个场景编写一个新脚本?

您需要获取数组的当前长度,因此不能超出当前数组范围。

enemyNo = Random.Range (0, enemies.Length)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM