2017-02-26 149 views
0

这是我在c#下面写的产卵脚本脚本应该在场景中随机创建对象。Unity3d脚本错误c#IndexOutOfRangeException:数组索引超出范围

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

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

我可以看到,可能会导致它如果spawnObjects数组是空的唯一的事。你有没有将GameObjects添加到检查器中的数组中?否则,你可以打印objectToSpawn,看看打印是什么,然后从那里开始。 –

+0

@JohanLindkvist; -/opps是的,就是这样,谢谢!让它成为答案,我会接受。 – Dano007

回答

2

IndexOutOfRange意味着你试图访问到不存在的数组的元素。

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

尝试Debug.Log(spawnObjects.Length):Instantiate之前,你会发现,其实你gameobjects的数组是空的,因为它会返回0。