- Home /
 
I have a audio source in one scene, I want it to continue when entering next scene
I have this audio source that's, let's say for example, playing a song.
You click a button and a new scene is loaded. How do I make the music continue from where it left off?
Thanks in advance!
Answer by Stormizin · May 27, 2013 at 12:04 PM
What you'd probably do is attach the AudioClip to a game object to which you also have attached a script which calls DontDestroyOnLoad. That way, the game object does not get destroyed when the new scene is loaded and audio should keep playing.
EDIT: Of course, if you have that game object in every scene, it will duplicate the sound. One solution to that is following what I call the "Unity Singleton" pattern which is kind of like the classic Singleton pattern but specific to Unity (this is C# because I find examples easier to understand in C# - UnityScript follows right below):
 public class MyUnitySingleton : MonoBehaviour {
  
     private static MyUnitySingleton instance = null;
     public static MyUnitySingleton Instance {
         get { return instance; }
     }
     void Awake() {
         if (instance != null && instance != this) {
             Destroy(this.gameObject);
             return;
         } else {
             instance = this;
         }
         DontDestroyOnLoad(this.gameObject);
     }
  
     // any other methods you need
 }
 
               What this basically does is: Check for an existing instance, if there already is an instances, destroy self - if not, store this is instance (so anyone who's coming later will destroy themselves). This also provides a public accessor so you can access the single instance from anywhere via MyUnitySingleton.Instance. Of course, you'd have your sound-specific methods also in that same class/script.
So here's (hopefully) the same in UnityScript (note that this must be in a file called "MyUnitySingleton" - or, in other words: replace any occurrence of "MyUnitySingleton" with the filename of your script):
 private static var instance:MyUnitySingleton;
 public static function GetInstance() : MyUnitySingleton {
 return instance;
 }
  
 function Awake() {
     if (instance != null && instance != this) {
         Destroy(this.gameObject);
         return;
     } else {
         instance = this;
     }
     DontDestroyOnLoad(this.gameObject);
 }
 
              Your answer