2017-02-26 724 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。

相關問題