title: Spawning enemies in Unity 2D
body: <p>I wanted to make my enemies appear from top using 'spawn' while rotating on itself.</p>
  
  <p>But I received this error: </p>
  
  <blockquote>
    <p>IndexOutOfRangeException: Array index is out of range.
    spawnScript.addEnemy () (at Assets/Scripts/spawnScript.cs:21)</p>
  </blockquote>
  
  <p>Below is my script:</p>
  
  <pre><code>using System.Collections;
  using System.Collections.Generic;
  using UnityEngine;
  
  public class spawnScript : MonoBehaviour {
  
  public Transform[] spawnPoints;
  public GameObject enemy;
  public float spawnTime = 5f;
  public float spawnDelay = 3f; 
  
  // Use this for initialization
  void Start () {
      InvokeRepeating ("addEnemy", spawnDelay, spawnTime);
  
  }
  
  void addEnemy() {
      // Instantiate a random enemy.
      int spawnPointIndex = Random.Range(0, spawnPoints.Length);
      Instantiate (enemy, spawnPoints[spawnPointIndex].position, spawnPoints[spawnPointIndex].rotation);
  }
  
  // Update is called once per frame
  void Update () {
  
  }
  }
  </code></pre>