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.
The problem I am having is my foreach statement keep returning null on "enemy"
"enemy" in this statement below is where the problem is
"GameObject enemy in pizzaEnemyList"
I do have one Gameobject inside of the list. Included in picture below
private List<GameObject> pizzaEnemyList = new List<GameObject> ();
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;
}
//Function I am using to add the enemies to the list.
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;
}

activeInHierarchyis indeed false for that item? (Are you sure it's only disabled, and not destroyed?) Also, you can usepizzaEnemy = enemyinstead ofpizzaEnemy = pizzaEnemyList [count], so you don't need to keep the counter variable.FetchPizzaEnemy()returningnull? Or isFetchPizzaEnemy()throwing aNullReferenceExceptionwhen trying to access theactiveInHierarchyproperty onenemy?pizzaEnemyListcause right now itsprivateso this means you're not adding them from the inspector in unity.