- Home /
Don't Destroy on Load return to scene Duplicate Music Object
I have a main menu scene and a options menu scene. I have a cube with no mesh rendered and an audio source with a 7 minute sound track that loops (the cube is in the main menu scene(first scene on start-up)). I have a script for the cube music player object that is do not destroy object on load when you switch to options menu. It works, when you switch to options menu, but when you switch back to main menu from options it creates another duplicate music playing cube so there is the don't destroy on load music cube that has been playing since beginning, and the new cube that restarts the track and now there are two versions playing. I need the same track that starts at the beginning when the game starts to keep playing when you switch to options menu and back to main menu, so that same track is always playing without duplicating or restarting. Please help, this bug is making me very distressed, as I and probably every other game developer have OCD and can not move on without fixing this. Thank you, Reece.
Answer by Lo0NuhtiK · Feb 07, 2015 at 04:28 PM
http://wiki.unity3d.com/index.php/Singleton
...and a more simple script for you to get started with ->
public class MusicPlayer : MonoBehaviour
{
private static MusicPlayer _instance ;
void Awake()
{
//if we don't have an [_instance] set yet
if(!_instance)
_instance = this ;
//otherwise, if we do, kill this thing
else
Destroy(this.gameObject) ;
DontDestroyOnLoad(this.gameObject) ;
}
}
Answer by DiegoSLTS · Feb 07, 2015 at 06:43 PM
Do not add the GameObject in the Main Menu scene using the editor, instantiate it with code on the Start or Awake method of a script that runs on Main Menu. Before the instatiation code, check that the GameObject for the music is not present so you only add it once: http://docs.unity3d.com/ScriptReference/GameObject.Find.html.
Next time you return to the scene the GameObject will already be there, so the code won't create a clone.
You can create a new GameObject and set the music component in code, or you can create a prefab of your current music GameObject and the instantiation takes just one line of code: http://docs.unity3d.com/Manual/InstantiatingPrefabs.html
there is a dot in the link. edited link: http://docs.unity3d.com/ScriptReference/GameObject.Find.html