Unity: Audio source gets destroyed after scene reloads

Viewed 458

I just introduced a pause option to my little testing game. I have audio in background (that plays throughout the whole game, even when the scene changes), so I've decided to make the music stop while the game is paused. For some reason, it works just fine UNTIL the game reloads/changes scene.
Then an error pops up

"The object of type 'AudioSource' has been destroyed."

Can anybody help? Also.. I thought it's a component, not an object! Might be both, I'm not sure.

How I make my music continuous:

void Awake()
{
    if (instance != null)
    {
        Destroy(gameObject);
    }
    else
    {
        instance = this;
        GameObject.DontDestroyOnLoad(gameObject);
    }      
}

My pause menu:

public static bool GameIsPaused = false;
public GameObject pauseMenuUI;
public AudioSource song;

void Update()
{
    if (Input.GetKeyDown(KeyCode.Escape))
    {
        if (GameIsPaused)
        {
            Resume();
        }
        else
        {
            Pause();
        }
    }
}

void Resume()
{
    pauseMenuUI.SetActive(false);
    Time.timeScale = 1f;
    GameIsPaused = false;
    song.mute = false;
}

void Pause()
{
    pauseMenuUI.SetActive(true);
    Time.timeScale = 0f;
    GameIsPaused = true;
    song.mute = true;
}

Thank you!

2 Answers

Your problem could be with this line here

 if (instance != null)

This is a singleton pattern and the purpose of this line is to prevent two instances of your singleton class from existing, which is a big no-no. This means if you try make a new object but one already exists, it will destroy the new object.
However, if Awake()is called again for any reason on the first singleton then it will see that the member instance is not null and promptly destroy itself.

A fix would be to change it to this:

 if (instance != null && instance != this)

This would prevent your singleton from destroying itself.

Pretty sure it's your audio variable in the pause menu script. I think the pause menu dissociates itself from that AudioSrouce on a new scene load. To check this, go into game mode and load a new scene. When in the new scene, go over to the hierarchy and click the GameObject with the pause menu script on it. Now check to see if the public var AudioSource has anything associate with it.

Related