Play Sound on Health = 0

Hello, first question! Sorry if it’s really common, I could not find it anywhere online.

My combat system constantly checks to see if the monster’s health is at <= 0. If it turns out to be zero the monster immediately dies. For play testing purposes it runs great, but now I’m trying to play a death sound from the AudioSource on that same health value check, and I’ve finally gotten it to play the sound AND destroy the object, but it plays the sound clip a thousand times and blows out my ear drums!

void deathSound()
{
	if (health <= 0)
	{
	GetComponent<AudioSource>().PlayOneShot(spiderDeath, 1.0f);
	Destroy(gameObject, spiderDeath.length);
	}
}

Thanks in advance if you can help with a cleaner code, this is the only thing I’ve found that works with my combat system!

This is happening because when the script Updates, it sees that the health is == 0 and plays the sound. This occurs every frame which causes your problem. You solved it correctly in your case if you only want the sound to play once before resetting the boolean. It seems to me like you just want a more efficient way of doing things.

What you could do instead might seem a bit complicated at the moment, but is a slightly less hacky solution. Instead of tracking the enemy’s health in the manager object, do so with it’s own script on the spider.

For a pseudo-code example:

Spider script 
{
     int health = 100
     CombatManagerScript cms

     void Update
     {
          if(health <= 0)
          {
               cms.PlaySound() 
               Destroy(gameObject)
          }
     }
}

And then add a new (public!) method to the manager script called PlaySound which will only play the sound once. This way the spider object handles its own health and you fix the bug without random booleans in your code.