继续在不同场景中播放音频 [英] Continues to play audio in different scenes
问题描述
在我的Unity项目中,有不同的菜单,并且每个菜单都是不同的场景.每个场景都有用于控制音乐的按钮.
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);
}
}
这是我的musicToogle功能.在每个场景中,音乐都会重新开始;在每个场景中,当我想要打开/关闭音乐时,我都会单击一个部署此代码的按钮.但是,我不希望音乐在每个场景更改时都重新开始,我希望恢复播放,并且希望能够控制每个场景中的音乐(打开/关闭).我怎样才能做到这一点 ?
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 ?
推荐答案
我的答案假设musicPlayer
变量是 AudioSource
.
My answer assumes that musicPlayer
variable is a type of AudioSource
.
实际上有两种方法可以做到这一点:
There are really two ways to do this:
1 .
使用musicPlayer.Pause();
暂停,然后播放音乐,然后使用musicPlayer.UnPause();
取消暂停.这样可以确保音乐恢复播放,而不是重新开始播放.
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.
在这种情况下,请在每个GameObject中将DontDestroyOnLoad(gameObject);
与AudioSource
一起使用,以使它们在下一场景中不会被破坏.
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 .存储AudioSource.time
值.下次加载它,然后将其应用到AudioSource
上,然后再播放.
2.Store the AudioSource.time
value. Load it next time then apply it to the AudioSource
before playing it.
您可以使用PlayerPrefs
来执行此操作,但是我更喜欢使用json和
You can use PlayerPrefs
to do this but I prefer to store with json and the DataSaver
class.
保存:
AudioSource musicPlayer;
AudioStatus aStat = new AudioStatus(musicPlayer.time);
//Save data from AudioStatus to a file named audioStat_1
DataSaver.saveData(aStat, "audioStat_1");
加载:
AudioSource musicPlayer;
AudioStatus loadedData = DataSaver.loadData<AudioStatus>("audioStat_1");
if (loadedData == null)
{
return;
}
musicPlayer.time = loadedData.audioTime;
musicPlayer.Play();
您的AudioStatus
课:
[Serializable]
public class AudioStatus
{
public float audioTime;
public AudioStatus(float currentTime)
{
audioTime = currentTime;
}
}
这篇关于继续在不同场景中播放音频的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!