- Home /
 
How to destroy an object if it already exist in a scene
Hello I'm new here I'm having a hard time with the Audio(BG Music) of my scene, I created a BG Music to my first scene that will continuously play even going to another scene. My problem is that if I go back to the that scene(first scene) where I put my BG Music it will play the BG Music again, making it double BG Music(x3,x4,x5.... As I go back to that scene again)
Sorry for my wrong grammar :)
BTW this is my code:
 function Awake()
 {
     if(GameObject.Find("TronBG") == 1)
     {
         Debug.Log("IF");
         Destroy(gameObject);
     }
     else
     {
         Debug.Log("ELSE");
         DontDestroyOnLoad(gameObject);
         SoundSource = gameObject.AddComponent(AudioSource);
         SoundSource.playOnAwake = false;
         SoundSource.rolloffMode = AudioRolloffMode.Logarithmic;
         SoundSource.loop = true;
             
     }
     
 }
 
              Answer by aldonaletto · Dec 15, 2013 at 03:52 PM
Use a static variable to reference the first TronBG object, and suicide any TronBG object at Awake when this variable has been set:
 static var bgAudio: GameObject;
 function Awake(){
   if (bgAudio){ // if bgAudio already references some object...
     Destroy(gameObject); // suicide
   } else { // if bgAudio is null, this is the first TronBG object:
     bgAudio = gameObject; // assign this one
     SoundSource = gameObject.AddComponent(AudioSource);
     SoundSource.playOnAwake = false;
     SoundSource.rolloffMode = AudioRolloffMode.Logarithmic;
     SoundSource.loop = true;
   }
 }
 
 
              Answer by KellyThomas · Dec 15, 2013 at 03:28 PM
If you give them a unique tag this will work:
 function Awake() {
     if (GameObject.FindGameObjectsWithTag(gameObject.tag).length > 1){
         Destroy(gameObject);
     }
     else {
         //initialize
     }
 }
 
               The second (or more) instance will find more than one object with their tag.
WOW! thanks a lot bro! :D Finaly I can pass my project in GameDev. :D $$anonymous$$y next problem is to convert it into an android game :D
Your answer