0
votes

I am making a game that has two scenes (menu scene and game scene). In the menu scene, I create an empty game object just for my music, which includes (audio source (music), button to mute the music, and my script. Here's the script:

public class Music : MonoBehaviour
{
    public static Music Instance;

    public AudioSource mainMusic;

    public GameObject musicOffImage;

    // Keep The Muic Playing In Diffrent Scene
    void Awake()
    {
        if (!Instance)
            Instance = this;
        else
            Destroy(this.gameObject);

        DontDestroyOnLoad(this.gameObject);
    }

    // Method Mute Button
    public void MusicOnOff()
    {

        if (mainMusic.isPlaying)
        {
            mainMusic.Pause();
            musicOffImage.SetActive(true);
        }
        else
        {
            mainMusic.UnPause();
            musicOffImage.SetActive(false);
        }

    }
}

With that script, I can play music in different scenes without reloading the music, and the button is working too, but the problem is when I go to the game scene and I back up to the menu scene, somehow the button didn't work. I think it's about the Destroy game object, but I am not sure how to fix it. Any help would mean a lot to me. Thanks.

1
Can you share your scene loading logic? - Aaron Hull
I'm voting to close this question as off-topic because this is an exact duplicate of stackoverflow.com/q/59694890/7111561 please stick to one account and rather use the recovery function! - derHugo

1 Answers

0
votes

I assume that everything the Music scripts needs is a child of it so that it is always fine.

However, after Destroy of the instance from the new scene, your buttons from the new scene loose the reference to the Music instance.

Since you have a Singleton there anyway you could as well (ab)use it and have this attached to your button itself

public MusicButton : MonoBehaviour
{
    public void MusicOn()
    {
        Music.Instance.MusicOnOff();
    }
}

And reference that instead in your button.

Also the image could e.g. register itself to the Music.Instance like e.g.

public MusicImage : MonoBehaviour
{
    private void Start() 
    {
        Music.Instance.musicOffImage = gameObject; 
        gameObject.SetActive(Music.Instance.mainMusic.isPlaying);
    }
}

Alternative

In your question you said all objects are child's of an empty object, however the only object that gets DontDestroyOnLoad is the Music one. The others will get destroyed and reloaded so all these references might get lost as well. You might probably rather DontDestroyOnLoad the entire empty object and only hide/show the button in certain scenes.