How to detect when all enemy ships are destroyed

Just completed the Argon Assault module and want to complete the game with a GAME OVER splash screen once all the enemy ships are destroyed via Destroy(gameObject, 0.5f);

I am trying to find a way of determining that all the enemy ships have been destroyed, but I can’t quite get a handle on it.

Should I try and build an array of remaining enemies each time one is killed and then end the game when the array is empty?

I found this line, so I have tagged all my enemy ships as ‘Enemy’.

GameObject enemies = GameObject.FindGameObjectsWithTag(“Enemy”);

I thought it would fill an array with only active enemy ships but it doesn’t seem to do that.

I have all my enemy ships in a Hierachy folder called ‘Enemy Ships’ which empties out as each enemy ship is destroyed.

Is that some sort of array itself?

Any suggestions most welcome.

Cheers

Steve

Hi Steve,

Welcome to our community! :slight_smile:

Should I try and build an array of remaining enemies each time one is killed and then end the game when the array is empty?

Yes, that could be an idea. Alternatively, you could remove a specific enemy from a List. Unlike arrays, Lists are mutable. Look for “C# method overload” if you don’t know this technique yet. It could be helpful.

I thought it would fill an array with only active enemy ships but it doesn’t seem to do that.

Do your enemies have got the “Enemy” tag? And are your enemies active when that line of code gets executed?

I have all my enemy ships in a Hierachy folder called ‘Enemy Ships’ which empties out as each enemy ship is destroyed.

If you have an “Enemy Ships” root object and the children are enemies, you could simply use transform.childCount to see how many enemies are “alive”.


See also:

Thanks Nina

James suggested this one too.

There seem to be a number of ways to reach the same point. :grin:

bool isEnemiesAlive;

void Update()
{
CountEnemies();
if (!isEnemiesAlive)
{
EndLevel();
}
}

void CountEnemies()
{
Enemy enemies = FindObjectsOfType();
if (enemies != null)
{
isEnemiesAlive = true;
}
else isEnemiesAlive = false;
}

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms