0
\$\begingroup\$

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());
        }
    }
}
\$\endgroup\$
  • 1
    \$\begingroup\$ 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;? \$\endgroup\$ – Vaillancourt Aug 22 at 19:56
  • 1
    \$\begingroup\$ I actually tried already, I will edit the question to add it, perhaps I did it in the wrong way \$\endgroup\$ – FSic Aug 22 at 20:04
0
\$\begingroup\$

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 :/

\$\endgroup\$
  • \$\begingroup\$ 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.) \$\endgroup\$ – Chillersanim Aug 23 at 9:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.