Issue with playing audio

Hi! I tried all the ways I know to solve this problem and none of them worked. I needed to add audio that would play while the Game Over Screen (which is “ds” GameObject in my script) is active. But for some reason, the script I wrote acts really weird. dsMusic (the music that should be played when “ds” is active) doesn’t play, but BackgroundMusic stops, as it should. If I put another sounds instead of the music I need, then they run and loop, although the sounds doesn’t have checkmark for “loop”. Here’s the script:

public class AudioController : MonoBehaviour {

    public static AudioController instance;

    public GameObject ds;

    public AudioSource ammo, enemyDeath, enemyShot, gunShot, health, backgroundMusic, dsMusic;

    private void Awake()
    {
        instance = this;
    }

    // Use this for initialization
    void Start () {
    }
   
    // Update is called once per frame
    void Update () {
        if(ds.activeSelf)
        {
            StopBackgroundMusic();
            dsMusic.Play();
        }
    }

    public void PlayAmmoPickup()
    {
        ammo.Stop();
        ammo.Play();
    }

    public void PlayEnemyDeath()
    {
        enemyDeath.Stop();
        enemyDeath.Play();
    }

    public void PlayHealthPickup()
    {
        health.Stop();
        health.Play();
    }

    public void PlayEnemyShot()
    {
        enemyShot.Stop();
        enemyShot.Play();
    }

    public void PlayGunShot()
    {
        gunShot.Stop();
        gunShot.Play();
    }

    public void StopBackgroundMusic()
    {
        backgroundMusic.Stop();
    }
}

What can I do to solve this problem?
Thanks for any help!

You are calling dsMusic.Play() every time through Update().

So, should I put “if” statement under an Update loop?

Only if that condition turns true once. You need a way (perhaps by using a bool ‘started’) to make sure you only execute it once.

1 Like

I solved this problem. I created an additional script and attached it to GameOverScreen object, which is disabled by default. In the Start loop of this script I assigned bool “isStarted” as true, and then in the Update loop of the first script (AudioController) I created the following “if” statement:

        if(isStarted == true)
        {
                StopBackgroundMusic();
                dsMusic.Play();
        }
        isStarted = false;

Congrats! A minor hint: move ‘isStarted = false’ inside the body of the if statement, so it too is only excuted once, not every time through Update. I’s a minor detail, but the logic is cleaner: only change it if it needs changing.