Change Background Music When Health = 0

Hi all,

I’m trying to figure out how to stop the active audio clip and change the background music to a different clip when my player health = 0. I’ve tried multiple answers but can’t make it work with my code. Thank you in advance.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class HealthController : MonoBehaviour
{

    [SerializeField] private float playerHealth;
    [SerializeField] private float maxHealth;
    [SerializeField] private Image healthImage;

    [SerializeField] private int damage;

    void Start()
    {

    }

    public void ButtonClick()
    {
        {
            playerHealth -= damage;

            UpdateHealth();
        }

    }

    private void UpdateHealth()
    {
        healthImage.fillAmount = playerHealth / maxHealth;

    }

   


}

Create a script you attach to the Audio source playing the background music. In this script:

public AudioClip DeathBackgroundMusic;

public void PlayDeathBackgroundMusic()
{
    AudioSource audioSource = GetComponent<AudioSource>();
     audioSource.Stop();
     audioSource.clip = 
DeathBackgroundMusic;
      audioSource.Play();
}

In your HealthController script:

 public UnityEngine.Events.UnityEvent OnDeath;

 public void ButtonClick()
 {
     playerHealth -= damage;
     UpdateHealth();
     if(playerHealth < 0)
         OnDeath.Invoke();
 }

Finally, add an entry in the OnDeath event of the HealthController , in the inspector, and provide your audio script with the PlayDeathBackgroundMusic function

Code not tested

Worked perfectly! Thank you for the well communicated answer, I definitely learned from it.