0
\$\begingroup\$

I'm working on a defense game that I need a way of knowing if every enemy in a wave is dead. I wanted to use a counter for it:

foreach (GameObject g in group1)
{
    if(g == dead) {
        deadCount++;
    }
}
if(deadCount == allEnemiesInWave)
{
    goToNextWave();
}

but I think it's not a safe or accurate way. Is there any better way?

Edit: This question is not like Check if all gameobjects are destroyed. In my question, I wanted to make a condition on many objects, in the other one, OP wanted to check if such objects existed.

\$\endgroup\$
2
  • 2
    \$\begingroup\$ Possible duplicate of Check if all gameobjects are destroyed \$\endgroup\$
    – DMGregory
    Oct 6, 2017 at 20:19
  • 3
    \$\begingroup\$ Re: your edit, you need to learn to think about game development problems more broadly. Checking how many objects are destroyed is just another flavour of checking a condition on many objects — "is destroyed" is just one possible condition. The same algorithms can apply to both cases (eg. loop over all instances and check if they all pass or update in an event-based way when one of the instances changes its condition — eg. on death) \$\endgroup\$
    – DMGregory
    Oct 6, 2017 at 20:48

1 Answer 1

3
\$\begingroup\$

If you don't need to count them, don't count them. Although it does not hurt to count them and compare with the size of the list, you can achieve the same thing with a boolean variable (pseudo-code):

bool areAllDead = true;
foreach (GameObject g in group1)
{
  if (g != dead) 
  {
    areAllDead = false;
    break;
  }
}

if (areAllDead)
{
  goToNextWave();
}

This code is a bit more explicit with it's intention.

In either cases, this will be unsafe if the code within the loop changes the size of your group1.

\$\endgroup\$
1
  • 3
    \$\begingroup\$ This is the right way to do it. It also has the advantage of not checking the entire collection every time it's called, which may be costly depending on how large the collection is and how often it's called. \$\endgroup\$
    – Ed Marty
    Oct 8, 2017 at 2:31

Not the answer you're looking for? Browse other questions tagged .