- Home /
Is there a better way to tell when enemies are dead?
void OnTriggerStay2D(Collider2D other) {
if (other.gameObject.tag == "Antagonist" || other.gameObject.tag == "Skeleton" || other.gameObject.tag == "Wizard")
{
AllEnemiesKilled = false;
}
else
{
AllEnemiesKilled = true;
}
}
I'm assuming I could use OnDestroy() and add an int for every enemy death and when it equals the number of enemies set the bool to true but I was kind of hoping to use this incase I want to randomize spawning later...
I forgot to mention this one isn't working consistently - it will say All enemies are dead when they aren't
yes it wouldn't work consistently and it's very inefficient. A way better way of doing it with collisions would be to call OverlapCircle() and check all the tags of the the collisions. But collisions is probably the most inefficient way of doing it especially OnTriggerStay, that is being called constantly. What you should be doing is using a static variable or adding all your enemies to a list. To do either of these ways it would be easier if your enemies were the same class or inherit from a common base class. I would look into the type object pattern, using scriptable objects, then you don't need to worry about inheritance. See my answer below.
Answer by sjos · Jan 21, 2021 at 07:28 PM
I think the best way to go would be adding an int for each time an enemy is spawned and subtracting each time an enemy dies. Would you care to elaborate on why randomized spawning wouldn't work with this method?
Yeah I guess that would work best - thanks for enlightening me
Answer by logicandchaos · Jan 21, 2021 at 08:47 PM
the simplest way to keep track of object instances is with a static variable.
class Enemy
{
public static int numberOfEnimies;
//constructor
Enemy()
{
numberOfEnemies++;
}
//deconstructor
~Enemy()
{
numberOfEnemies--;
}
}
Then you get the number of enemies anytime by calling Enemy.numberOfEnemies you use the class name not the instance name because it is a static variable. Static variables are shared amongst instances of a class. You can also do Enemy enemy1; enemy1.numberOfEnemies; you can access it through the instance and no matter what instance it's called from it will give the same amount. Here is how you do it with MonoBehaviours:
class Enemy : MonoBehaviour
{
public static int numberOfEnimies;
Start()
{
numberOfEnemies++;
}
OnDestroy()
{
numberOfEnemies--;
}
}
If you are instantiating and destroying your objects, if you are enabling and disabling them than you do it like this instead:
class Enemy : MonoBehaviour
{
public static int numberOfEnimies;
OnEnable()
{
numberOfEnemies++;
}
OnDisable()
{
numberOfEnemies--;
}
}
Or you can have all your enemies in a list and use list.Count:
List<Enemy> enemies;
enemies.Count;