Continues to play audio in different scenes

一世执手 提交于 2019-12-02 12:00:46

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

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

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