- Home /
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;
}
}
Answer by Hellium · Feb 08, 2021 at 12:48 AM
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.
Your answer
![](https://koobas.hobune.stream/wayback/20220613024752im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Health bar goes down instantly. 1 Answer
floating health bar above gameobject mobile game 1 Answer
What is your solution? (Zombie Sounds) 1 Answer
I've got strange sound distorsion when I trigger a sound 0 Answers
How to make a health bar? 1 Answer