Search code examples
c#unity-game-enginescene

Continues to play audio in different scenes


In my Unity Project, there are different menus, and each menu is a different scene. Each scene has button for controlling the music.

public void musicToggle(GameObject Off){
        if (PlayerPrefs.GetInt ("Music") == 1) {
            musicPlayer.Stop ();
            Debug.Log ("Stop 2");
            PlayerPrefs.SetInt ("Music", 0);
            Off.SetActive(true);
        }
        else {
            musicPlayer.Play ();
            Debug.Log ("Play 2");
            PlayerPrefs.SetInt ("Music", 1);
            Off.SetActive (false);
        }
    }

This is my musicToogle function. In every scene the music restarts, and in every scene when I want to turn on/off the music, I click a button which deploys this code. However, I don't want the music to restart every scene change, I want it to resume, and I want to be able to control the music(turn on/off) in every scene. How can I do this ?


Solution

  • My answer assumes that musicPlayer variable is a type of AudioSource.

    There are really two ways to do this:

    1.Instead of using musicPlayer.Stop to stop the music,

    Use musicPlayer.Pause(); to pause then music then use musicPlayer.UnPause(); to un-pause it. This will make sure that the music resumes instead of restarting it.

    In this case, you use DontDestroyOnLoad(gameObject); on each GameObject with the AudioSource so that they are not destroyed when you are on the next scene.


    2.Store the AudioSource.time value. Load it next time then apply it to the AudioSource before playing it.

    You can use PlayerPrefs to do this but I prefer to store with json and the DataSaver class.

    Save:

    AudioSource musicPlayer;
    AudioStatus aStat = new AudioStatus(musicPlayer.time);
    //Save data from AudioStatus to a file named audioStat_1
    DataSaver.saveData(aStat, "audioStat_1");
    

    Load:

    AudioSource musicPlayer;
    AudioStatus loadedData = DataSaver.loadData<AudioStatus>("audioStat_1");
    if (loadedData == null)
    {
        return;
    }
    musicPlayer.time = loadedData.audioTime;
    musicPlayer.Play();
    

    Your AudioStatus class:

    [Serializable]
    public class AudioStatus
    {
    
        public float audioTime;
    
        public AudioStatus(float currentTime)
        {
            audioTime = currentTime;
        }
    }