- Home /
overlapping hear a song
void Awake ()
{
DontDestroyOnLoad (GameObject.Find ("MenuSound"). GameObject);
}
Thank you.
but, have a problem.
Every time move the scene, the two layers of overlapping hear a song.
Answer by AlucardJay · Apr 04, 2013 at 02:10 PM
From my answer here : http://answers.unity3d.com/questions/375227/music-continued-in-the-all-level.html
When this question comes up, DontDestroyOnLoad is the answer given, but it is only half the solution. For example, if you load the scene where the music player is created, then a duplicate is made, now you have 2 players following you through all the scenes. It took me a while to find the solution, but the answer is to use a Singleton . Search singletons on this 'site (or in google search "unity singleton") as there would be better explanations than what I could give.
The simple version is : only one instance of a singleton exists at a time, two cannot exist. It can be called by all scripts by using a static variable. So only one, and it has a variable which other scripts can reference.
Here is the script for a working singleton, just attach it to the music player. Note : this is in unity JS, and the script must be called MusicSingleton :
#pragma strict
// change the class name here to the name of your script, e.g.
// public class ThisIsTheScriptNameHere extends MonoBehaviour
public class MusicSingleton extends MonoBehaviour
{
private static var instance : MusicSingleton;
function Awake()
{
if (instance != null && instance != this)
{
Destroy( this.gameObject );
return;
}
else
{
instance = this;
}
DontDestroyOnLoad( this.gameObject );
}
// also change this to your script name
// public static function GetInstance() : ThisIsTheScriptNameHere
public static function GetInstance() : MusicSingleton
{
return instance;
}
function Update()
{
//
}
}
from my answer here : http://answers.unity3d.com/questions/334376/how-i-can-prevent-music-from-stopping-after-changi.html
This is the question I originally asked when I started : http://answers.unity3d.com/questions/235417/how-do-i-create-a-static-instance-in-javascript.html