- Home /
Other
how to changes music tracks along with scene changes?
Hi: i try to use a music manager to control music playing, like one music track matching one scene. i want it to turn the music from one to another automatically when i enter a new scene. i keep the music manager gameobject don't be destroyed between scenes by using singleton pattern, because i want it to control music volume. this is the code i tried, it doesn't work, it only keep playing the first track.
public class AudioManager : MonoBehaviour {
#region Singleton
private static AudioManager _instance;
public static AudioManager Instance
{
get
{
if (_instance==null)
{
_instance = GameObject.FindObjectOfType<AudioManager>();
DontDestroyOnLoad(_instance.gameObject);
}
return _instance;
}
}
#endregion
AudioSource musicPlayer;
public AudioClip Level01Music;
public AudioClip Level02Music;
public AudioClip Level03Music;
private void Awake()
{
#region SingletonRun
if (_instance==null)
{
_instance = this;
DontDestroyOnLoad(this);
}
else
{
if ( this !=_instance)
{
Destroy(this.gameObject);
}
}
#endregion
}
// Use this for initialization
void Start () {
musicPlayer = GetComponent<AudioSource>();
levelMusicPlay();
}
// Update is called once per frame
void Update () {
}
void levelMusicPlay()
{
Scene currentScene = SceneManager.GetActiveScene();
if (currentScene.name== "Level 01")
{
if (Level01Music != null)
{
musicPlayer.clip = Level01Music;
musicPlayer.Play();
}
else
{
Debug.LogWarning("Can not find level01Music");
}
}
if (currentScene.name == "Level 02")
{
if (Level02Music != null)
{
musicPlayer.clip = Level02Music;
musicPlayer.Play();
}
else
{
Debug.LogWarning("Can not find level02Music");
}
}
if (currentScene.name == "Level 03")
{
if (Level03Music != null)
{
musicPlayer.clip = Level03Music;
musicPlayer.Play();
}
else
{
Debug.LogWarning("Can not find level03Music");
}
}
}
}
is there any way to achieve my goal? Do an audiomixer will help? thank you.
Answer by TheSOULDev · Aug 16, 2017 at 04:47 PM
Your music change script is only called the first time the script is loaded. Because you're not destroying the object carrying the script, it will never be reloaded, and Start() won't be called. I don't know why you don't want it to be destroyed as destroying it would fix your problem of the music not changing. If you want to keep the volume, you could save the state of the music settings, save a "launch parameters" file loaded upon a scene change which will determine what data you'll load in a new scene. Otherwise, you could get some other game object that is loaded on a new scene which will run musicPlayer.Play on start.
Follow this Question
Related Questions
Destroy "Don'tDestroyOnLoad" script in a specific scene ?? 3 Answers
Music trackers and iOS 0 Answers
adding music to the main menu screen 0 Answers
.wav file not working 2 Answers
Large music files make asset importing slow / game large. Compression ideas? 0 Answers