title: Destroy the gameobjects of an array
body: <p>I have an array to instantiate multiple gameobjects when the player enters on a trigger but I don't know how to destroy these gameobjects when the player exits the trigger. This is my code:</p>
  
  <pre><code>using UnityEngine;
  using System.Collections;
  using System.Collections.Generic;
  
  public class SpawnDestroy : MonoBehaviour {
  
  public List&lt;GameObject&gt; spawnPositions;
  public List&lt;GameObject&gt; spawnObjects;
  
  
  void OnTriggerEnter(Collider other)
  {
  
      if (other.gameObject.tag == "Player")
      {
          SpawnObjects ();
      }
  }
  
  void OnTriggerExit(Collider other)
  {
  
      if (other.gameObject.tag == "Player")
      {
  
      ............
  
      }
  }
  
  void SpawnObjects()
  {
      foreach(GameObject spawnPosition in spawnPositions)
      {
          int selection = Random.Range(0, spawnObjects.Count);
          Instantiate(spawnObjects[selection], spawnPosition.transform.position, spawnPosition.transform.rotation);
      }
  }
  
  }
  </code></pre>
  
  <p>UPDATE CODE:</p>
  
  <pre><code>using UnityEngine;
  using System.Collections;
  using System.Collections.Generic;
  
  
  public class SpawnDestroy : MonoBehaviour {
  
  public List&lt;GameObject&gt; spawnPositions;
  public List&lt;GameObject&gt; spawnObjects;
  private List&lt;GameObject&gt; instantiated;
  
  
  void OnTriggerEnter(Collider other)
  {
  
      if (other.gameObject.tag == "Player")
      {
          SpawnObjects ();
      }
  }
  
  void OnTriggerExit(Collider other)
  {
  
      if (other.gameObject.tag == "Player")
      {
  
          for(int i = 0; i &lt; instantiated.Count; i++)
          {
              Destroy(instantiated[i]);
          }
  
          }
  }
  
  void SpawnObjects()
  {
      // (re-)initialize as empty list
      instantiated = new List&lt;GameObject&gt;();
  
      foreach(GameObject spawnPosition in spawnPositions)
      {
          int selection = Random.Range(0, spawnObjects.Count);
          instantiated.Add(Instantiate(spawnObjects[selection], spawnPosition.transform.position, spawnPosition.transform.rotation));
      }
  }
  
  }
  </code></pre>