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

唯一のものを返しますよう、実際にゲームオブジェクトのあなたの配列が空であることがわかります。インスペクタの配列にGameObjectsを追加しましたか?そうでなければ、objectToSpawnを印刷して、何が印刷物であるかを見てそこから行くことができます。 –

+0

@JohanLindkvist; -/oppsはいそれでした、ありがとう!それを答えると私は受け入れます。 – Dano007

答えて

2

IndexOutOfRangeあなたは存在しない配列の要素にアクセスしようとしたことを意味します。

Random.Range (0, spawnObjects.Length);を使用している場合のケースでは、唯一可能なケースは配列が空であることです。

InstantiateDebug.Log(spawnObjects.Length):に試してみて、あなたはそれが私がspawnObjects配列が空の場合、それはある引き起こす可能性があります見ることができます0

関連する問題