title: Null GameObjects in foreach loop
body: <p>I am trying to iterate through a list of GameObjects and find the first GameObject that is not active in the hierarchy and return that GameObject. </p>
  
  <p>The problem I am having is my foreach statement keep returning null on "enemy"</p>
  
  <p>"enemy" in this statement below is where the problem is</p>
  
  <p>"GameObject enemy in pizzaEnemyList"</p>
  
  <p>I do have one Gameobject inside of the list. Included in picture below</p>
  
  <pre><code>private List&lt;GameObject&gt; pizzaEnemyList = new List&lt;GameObject&gt; ();
  
  private GameObject FetchPizzaEnemy()
  {
      GameObject pizzaEnemy = null;
      int count = 0;
  
      foreach (GameObject enemy in pizzaEnemyList)
      {
          if (enemy.activeInHierarchy == false)
          {
              pizzaEnemy = pizzaEnemyList [count];
  
              pizzaEnemyList.Remove (enemy);
  
  
              return pizzaEnemy;
          }
          count += 1;
      }
  
      return pizzaEnemy;
  }
  </code></pre>
  
  <p>//Function I am using to add the enemies to the list. </p>
  
  <pre><code>public void DeactivateAndStoreEnemy(GameObject enemy)
  {
      //decativates the enemy
      enemy.SetActive(false);
  
  
  
      //Store the enemy into the correct list
      if (enemy.name == "PizzaGuy")
      {
          pizzaEnemyList.Add (enemy);
      }
      else if (enemy.name == "FiresGuy")
      {
          friesEnemyList.Add (enemy);
      }
      else if (enemy.name == "SodaGuy")
      {
          sodaEnemyList.Add (enemy);
      }
  }
  
  
  public int PizzaListUnactiveEnemyCount()
  {
      int unactiveEnemiesCount  = 0;
  
      foreach (GameObject enemies in pizzaEnemyList)
      {
          if (enemies.activeInHierarchy == false)
          {
              unactiveEnemiesCount += 1;
          }
      }
  
      return unactiveEnemiesCount;
  }
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/uRvSn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uRvSn.png" alt="enter image description here"></a></p>