title: Unity3d scripting error c# IndexOutOfRangeException: Array index is out of range
body: <p>This is my spawning script belowwritten in c# The script should create objects randomly in the scene.</p>
  
  <p>The issue is that I'm getting this error at runtime.</p>
  
  <pre><code>IndexOutOfRangeException: Array index is out of range.
  CreateEasterEggs.MakeThingToSpawn () (at Assets/CreateEasterEggs.cs:52)
  CreateEasterEggs.Update () (at Assets/CreateEasterEggs.cs:28)
  </code></pre>
  
  <p>Not sure what I have done wrong, thinking its something to do with the game object?</p>
  
  <p>Thank you.</p>
  
  <hr>
  
  <pre><code>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  &gt;= 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 &lt; 4 &amp;&amp; spawnPosition.z &gt; -4) || (spawnPosition.x &lt; 4 &amp;&amp; spawnPosition.x &gt; -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;
        }
   }
  </code></pre>