Destroy is too slow and leads to method getting called multiple times

I have 2 players in my game, both have the ability to shoot bullets at enemies.

Killing an enemy adds 100 to the score.

The enemy also gets destroyed.

The problem is, if 2 (or more) bullets hit an enemy at the same time the score is added twice.


My attempts to fix the issue:

  • Add a bool to check if the enemy is currently taking damage
  • Using DestroyImmediate() instead of Destroy()

Both didn’t work.

Hy, i would try to do something like this in your enemy script:

bool isAlive = true;
int health = 100;

public void GetDamage(int dmg, int playerID = 1)
{
     health -= dmg;

     if (isAlive && health <= 0)
     {
          ScoreManager.SetScore(playerID, 100);

          isAlive = false;
          Destroy(gameObject);
     }
}

This way, its not possible to set the score twice, even if the hits happen at the same frame.