Unity3d脚本错误c#IndexOutOfRangeException:数组索引超出范围

时间:2017-02-26 09:23:30

标签: c# unity3d unity5

这是我在c#中编写的产卵脚本。脚本应该在场景中随机创建对象。

问题是我在运行时遇到了这个错误。

IndexOutOfRangeException: Array index is out of range.
CreateEasterEggs.MakeThingToSpawn () (at Assets/CreateEasterEggs.cs:52)
CreateEasterEggs.Update () (at Assets/CreateEasterEggs.cs:28)

不确定我做错了什么,认为它与游戏对象有关?

谢谢。

using UnityEngine;
 using System.Collections;

 public class CreateEasterEggs : MonoBehaviour
 {
     public float secondsBetweenSpawning = 0.1f;
     public float xMinRange = -25.0f;
     public float xMaxRange = 25.0f;
     public float yMinRange = -5.0f;
     public float yMaxRange = 0.0f;
     public float zMinRange = -25.0f;
     public float zMaxRange = 25.0f;
     public GameObject[] spawnObjects; // what prefabs to spawn

     private float nextSpawnTime;

     void Start ()
     {
         // determine when to spawn the next object
         nextSpawnTime = Time.time+secondsBetweenSpawning;
     }

     void Update ()
     {
         // if time to spawn a new game object
         if (Time.time  >= nextSpawnTime) {
             // Spawn the game object through function below
             MakeThingToSpawn ();

             // determine the next time to spawn the object
             nextSpawnTime = Time.time+secondsBetweenSpawning;
         }   
     }

    void MakeThingToSpawn ()
      {
          //Start the vector at an invalid position
          Vector3 spawnPosition = new Vector3(0, 0, 0);

          //while we are not in the right range, continually regenerate the position
          while ((spawnPosition.z < 4 && spawnPosition.z > -4) || (spawnPosition.x < 4 && spawnPosition.x > -4)) 
          {
              spawnPosition.x = Random.Range (xMinRange, xMaxRange);
              spawnPosition.y = Random.Range (yMinRange, yMaxRange);
              spawnPosition.z = Random.Range (zMinRange, zMaxRange);
          }

          // determine which object to spawn
          int objectToSpawn = Random.Range (0, spawnObjects.Length);

          // actually spawn the game object
              GameObject spawnedObject = Instantiate (spawnObjects [objectToSpawn], spawnPosition, transform.rotation) as GameObject;

          // make the parent the spawner so hierarchy doesn't get super messy
          spawnedObject.transform.parent = gameObject.transform;
      }
 }

1 个答案:

答案 0 :(得分:2)

IndexOutOfRange表示您尝试访问不存在的数组元素。

在您使用Random.Range (0, spawnObjects.Length);的情况下,唯一可能的情况是您的数组是空的。

Debug.Log(spawnObjects.Length):之前尝试Instantiate,你会发现实际上你的游戏对象数组是空的,因为它会返回0。