- Home /
Music does not play between scenes
Hi guys, I was designing a scene of my project and everything worked normally, including the sound, but I realized that the editor and build the sound that plays in loop located on the ground scene does not. Only in scenes exchanges it does not work, starting from the actual scene it usually works. Can anyone tell the point?
But what happens is that any sound from the scene after the menu scene is played, I only realized this when I build, because before I just compiling this single scene and sounds worked, but when I build the project with every scene only the menu music is played.
Answer by engieelec · Oct 08, 2015 at 12:20 AM
public static MusicManager instance = null;
private AudioSource audioSource;
void Awake()
{
if(instance == null)
{
instance = this;
}
else if(instance != this)
{
Destroy (gameObject);
}
DontDestroyOnLoad(gameObject);
audioSource = GetComponent<AudioSource>();
}
Create a "MusicManager" singleton and instantiate it in your first scene. Add an audio source to it and a collection of music clips that you would like to play. Also add a few methods to indicate which clip to play.
@engieelec I do not understand: when changing scene all previous scene objects are destroyed and the new instanced scene, why the need for a $$anonymous$$usic$$anonymous$$anager? It also gave error on this line: public static $$anonymous$$usic$$anonymous$$anager instance = null; (I have not used it, I tried to create a GameObject in the first scene with that name and did not work)
This singleton instance will not be destroyed if a scene is changed. It will persist.
You would need to create a script called $$anonymous$$usic$$anonymous$$anager
Add the above code
Create an empty object in your scene and add a script to it
Add an Audio Source to the object
Create a collection of Audio Clips to play (like an array) and make it public
Add all of your sound clips to the collection
Create a prefab of the $$anonymous$$usic$$anonymous$$anager object and delete the original one in your scene
Now, you can instantiate the $$anonymous$$usic$$anonymous$$anager in your first scene:
Create an empty game object called Launcher or some other name
Add a script to it with this:
public class Launcher : $$anonymous$$onoBehaviour {
public GameObject $$anonymous$$usic$$anonymous$$anager; void Awake() { Instantiate($$anonymous$$usic$$anonymous$$anager); } }
Drag the $$anonymous$$usic$$anonymous$$anager prefab on
Change your scenes
Notice that the "Launcher" is gone but "$$anonymous$$usic$$anonymous$$anager" persists between scenes.
You can go back to your $$anonymous$$usic$$anonymous$$anager script and add methods to play music clips and then call the $$anonymous$$usic$$anonymous$$anager instance elsewhere in your implementation like:
$$anonymous$$usic$$anonymous$$anager.instance.doSomeThing();