Continues to play audio in different scenes

2019-03-06 11:38发布

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 ?

标签: c# unity3d scene
2条回答
倾城 Initia
2楼-- · 2019-03-06 12:11

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;
    }
}
查看更多
爷的心禁止访问
3楼-- · 2019-03-06 12:17

You will need to create a singleton class and instantiate it on your first scene, then you can pass it around your various scenes as described in this unity answer: http://answers.unity3d.com/answers/12176/view.html

查看更多
登录 后发表回答