Continues to play audio in different scenes

[亡魂溺海] 提交于 2019-12-04 06:43:55

问题


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 ?


回答1:


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;
    }
}



回答2:


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



来源:https://stackoverflow.com/questions/46181506/continues-to-play-audio-in-different-scenes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!