- Home /
two deaths of one object at once
Hi, here is my code
public void Hit(int damage)
{
currentHealth -= damage;
// If the current health is less than or equal to zero...
if (currentHealth <= 0)
{
// ... the enemy is dead.
Death ();
}
}
void Death ()
{
Instantiate(explosion, transform.position, transform.rotation);
gameController.AddScore (scoreValue);
Destroy (gameObject);
}
In most cases it works perfectly but sometime I have two explosions at once. I think that two different bullets kill the object at once and I get two explosions and double score. Could someone suggest me a solution? I would appreciaste it :)
Answer by KoenigX3 · May 29, 2020 at 01:57 PM
Either create a boolean value dead and use it to determine whether Death was called already, or stop Hit from being processed after it takes another bullet when the character has 0 or less health.
bool dead = false;
public void Hit(int damage)
{
currentHealth -= damage;
if(currentHealth <= 0 && !dead) Death();
}
void Death()
{
dead = true;
// The rest of the code
}
The second option:
public void Hit(int damage)
{
if(currentHealth <= 0) return;
currentHealth -= damage;
if(currentHealth <= 0) Death();
{
Your answer
Follow this Question
Related Questions
Play method only ONCE when detected by the update function 2 Answers
camera orbiting dead 0 Answers
Character disappears when dies. 3 Answers
How to make my enemy stop moving once dead? 2 Answers
Help with player death on collision! 2 Answers