Audio Source wont play in if statement

I have two Audio Sources on my Player. One is the audio source from the fps controller and another is a heartbeat sound that is supposed to play when the player gets below a certain health. The heartbeat will play if I play it in the start function, but won’t play if I place it in an if statement during the update function.

private AudioSource[] audioSource;
private AudioSource heartbeat;   

 void Start () {
        //audioSource = GetComponent<AudioSource>();
        audioSource = GetComponents<AudioSource>();
        heartbeat = audioSource[1];

    }	

void Update () {
		if(health <= 25)
        {
            Debug.Log("Beating");
            heartbeat.Play();

        }
        Debug.Log(health);

    
	}

Probably it’s being called 60-200 times per second, which is the average FPS for testing scenes. Basically you are relaunching the sound so fast it can’t get anywhere near the begining of the sound. Try adding a check if it’s already playing.

Remove the update method and make a user defined method there. Then call that method from another script (probably from where your player is getting hit).

@johntc121
Turn on and off the volume rather than repeatedly playing it, or fix up the if statement to only be called once.

         if(health <= 25)
         {
             //Debug.Log("Beating");
             heartbeat.volume = 1;
         } else {
             heartbeat.volume = 0;
         }

This also allows you to have a smooth transitioning into it, by slowly incrementing the volume with a temporary variable.

Hope this fixes your problem!