# PlayClipAtPoint() playing multiple times on enemy death

I am having problems with PLayClipAtPoint(). I want to play a given sound as soon as a gameObject is destroyed. Here is my code (the concerned parts):

void Update()
{
if (health <= 0)
{
StartCoroutine(Death());
}
}

public IEnumerator Death() {
anim.SetBool("isDying", true);
AudioSource.PlayClipAtPoint(dmgSounds[0], transform.position);
Destroy(gameObject, 3f);

yield return null;
}


I assume that the problem is due to the fact that as soon as the conditions are achieved, in this case the health reaching zero, the coroutine starts and it will keep starting for each frame, but how else should I call it? Anybody has some hint to give?

EDIT: I have already tried to wrap the logic in a bool as suggested in the comment so that it would work only when the bool condition is valid, without success. Here is the code with the flag bool:

void Update()
{
if (health <= 0)
{
if(isAlive){
isAlive = false;
StartCoroutine(Death());
}
}
}

• What about setting a bool flag to your object and setting it to true when the object dies and you start the coroutine, and don't call the coroutine again if the bool == true;? Aug 22, 2019 at 19:56
• I actually tried already, I will edit the question to add it, perhaps I did it in the wrong way
– FSic
Aug 22, 2019 at 20:04

The comment actually gave me another idea which in the end worked. I previously created for other needs a set of states, so I just created another one for the death state and it did the trick!

    void Update()
{
if (health <= 0 && currentState != EnemyState.die )
{
StartCoroutine(Death());
currentState = EnemyState.die;
}
}


I wonder however why it did not work using a simple bool :/

• A simple bool should have worked. What was happening instead? I can think of two things: 1) The subroutine never got called because isAlive was never set to true. 2) The subroutine kept on getting called because somewhere isAlive was set back to true. (I edited this comment as the old comment was imprecise.) Aug 23, 2019 at 9:06