How to stop the main music and play the GameOver music when a player dies?
Hi there,
I want to stop the main music and play GameOver music when a player dies. Somehow the main music will keep playing and the GameOver music won't play when the player is dying. Can anyone here help me, please?
Unity Version: 2020.1.10
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class SOUND_EFFECTS : $$anonymous$$onoBehaviour {
public AudioSource level$$anonymous$$usic;
public AudioSource deathSong;
public bool levelSong = true;
public bool DeathSong = false;
void Start () {
}
void Update () {
}
public void Level$$anonymous$$usic()
{
levelSong = true;
DeathSong = false;
level$$anonymous$$usic.Play();
}
public void DeathSound()
{
if (level$$anonymous$$usic.isPlaying)
levelSong = false;
{
level$$anonymous$$usic.Stop();
}
if (!deathSong.isPlaying && DeathSong == false)
{
deathSong.Play();
DeathSong = true;
}
}
}
Answer by SteveHoward · Nov 02, 2020 at 04:06 PM
@Uoe , I'm not sure what is wrong, but it sounds like DeathSound() is not being called. Put a Debug.Log() as the first line in DeathSound() so you can see if it is getting called. If it is not, then try some Debug.Log() in the code that is supposed to be calling it.
Also your first if statement is a little funky. levelSong = false; will be executed when the if clause is true. It is also the end of the if statement. levelMusic.Stop(); will always be executed because it is outside of the if statement. My guess is you want:
if (levelMusic.isPlaying) { levelSong = false; levelMusic.Stop(); }
instead so both statement are part of the if statement.
Steve
Answer by Uoe · Nov 03, 2020 at 03:13 PM
Hi @SteveHoward,
Many thanks for your quick response.
I finally figure it out what was my mistake. I had to call the Gameover script from my player's health script. Once I typed " FindObjectOfType().DeathSound(); I was able to hear the dead music after my player's death.
Thanks for your help tho!! Have a good day!
Cheers!!