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 ?
My answer assumes that
musicPlayer
variable is a type ofAudioSource
.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 usemusicPlayer.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 theAudioSource
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 theAudioSource
before playing it.You can use
PlayerPrefs
to do this but I prefer to store with json and theDataSaver
class.Save:
Load:
Your
AudioStatus
class: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