• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
11
Question by Rimrook · Feb 10, 2010 at 06:59 AM · audioscene

Audio or Music to continue playing between scene changes

Is there a simple way to have audio like a background music track to carry over to another scene without stopping or restarting?

I've found a script similar but it was more like a jukebox and it was in C#, I'm still baby-stepping through Javascript.

Comment
Add comment · Show 1
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image degeta · Sep 16, 2016 at 06:06 PM 0
Share

what if that audio is still playing in the scene that doesnt require that audio.? How to stop it?

17 Replies

· Add your reply
  • Sort: 
avatar image
48
Best Answer

Answer by jashan · Feb 10, 2010 at 07:16 AM

What you'd probably do is attach the AudioClip to a game object to w$$anonymous$$ch you also have attached a script w$$anonymous$$ch 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 w$$anonymous$$ch is kind of like the classic Singleton pattern but specific to Unity (t$$anonymous$$s 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 != t$$anonymous$$s) {
         Destroy(t$$anonymous$$s.gameObject);
         return;
     } else {
         instance = t$$anonymous$$s;
     }
     DontDestroyOnLoad(t$$anonymous$$s.gameObject);
 }

 // any other methods you need

}

What t$$anonymous$$s basically does is: Check for an existing instance, if there already is an instances, destroy self - if not, store t$$anonymous$$s is instance (so anyone who's coming later will destroy themselves). T$$anonymous$$s 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 t$$anonymous$$s 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 != t$$anonymous$$s) { Destroy(t$$anonymous$$s.gameObject); return; } else { instance = t$$anonymous$$s; } DontDestroyOnLoad(t$$anonymous$$s.gameObject); }

Comment
Add comment · Show 13 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Rimrook · Feb 12, 2010 at 02:14 PM 0
Share

That's great, but now how do I get it to stop, not play again and overlap when the scene is reloaded, or the music track changes altogether? DonDestroyOnLoad works too well. :)

avatar image jashan · Feb 12, 2010 at 05:22 PM 0
Share

Ah, you probably have that same object in the scene your loading as well, right? In that case you need to make sure there's only one instance of the object. Do so by adding a static variable "instance" and assigning it on Awake(); also check if it already is assigned, and if it is - destroy the object.

avatar image rahulpatil6220375 jashan · Jan 29, 2019 at 10:31 AM 0
Share

when user go to setting and audio off and user quite a game then come audio off?

avatar image Rimrook · Feb 16, 2010 at 06:12 PM 0
Share

Still having a lot of trouble with this. I imagine the easiest way to set up a BGM system is to have a script identify a track being played. If it is the same, don't play the audio. If it is different, stop the existing one and play the new one. Then some how have this script on every scene so that the music is always correct for that scene no matter what. Then again this might be beyond my current skill level with Javascript.

avatar image jashan · Feb 17, 2010 at 02:46 PM 0
Share

I think I'll edit my original posting to contain some more specifics which will hopefully clarify things for you.

avatar image jashan · Feb 17, 2010 at 03:36 PM 1
Share

... the advantage of using the Singleton pattern as outlined above is that you don't have to worry about which song is played when switching a scene because there's not change in the audio when you do that. Of course, you need a separate mechanism of controlling which song is played (and you'd integrate that into this Singleton class ... you might call it MusicManager or something like that).

Show more comments
avatar image
12
Best Answer

Answer by Rimrook · Feb 26, 2010 at 07:46 AM

Ok, I've eventually answered my own question. For great justice, I'll post my findings for others to see/nab/yank/freeb. The code is simple to use, and extremely handy.

First, on your title screen or whatever is your first scene, add t$$anonymous$$s script to a game object with an audio source. Name t$$anonymous$$s game object "Game Music".

private static var instance:MyUnitySingleton; public static function GetInstance() : MyUnitySingleton { return instance; }

function Awake() { if (instance != null && instance != t$$anonymous$$s) { Destroy(t$$anonymous$$s.gameObject); return; } else { instance = t$$anonymous$$s; } DontDestroyOnLoad(t$$anonymous$$s.gameObject); }

(That bit of code was kindly provided by Jashan, thank you Jashan.) Create a new empty game object and add a "Music Manager" script to it.

Var NewMusic: AudioClip; //Pick an audio track to play.

function Awake () { var go = GameObject.Find("Game Music"); //Finds the game object called Game Music, if it goes by a different name, change t$$anonymous$$s. go.audio.clip = NewMusic; //Replaces the old audio with the new one set in the inspector. go.audio.Play(); //Plays the audio. }

Have t$$anonymous$$s Music Manager in your scenes. If it is different, it will change the music. If it is the same, it will keep playing and won't be interrupted by level loads or anyt$$anonymous$$ng. To stop the music, use the Music Manager and select None for the audio. Alternatively, you can always tell the Game Music object to stop its audio to and all those commands that go with it. I suggest never really destroying it, t$$anonymous$$s one object can set the music for your entire game.

I hope you like it.

Comment
Add comment · Show 4 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Silverfell-2 · May 27, 2010 at 02:43 PM 0
Share

I don't get the code. If you're declaring a singleton, why then go and grab your object by 'Find'? Could you not just access it by Gamemusic.singleton.whatever?

avatar image hankphone · Sep 29, 2010 at 09:43 PM 0
Share

Change "Var" to "var" in line one of second script.

avatar image ali rizvi · Jul 29, 2013 at 02:30 AM 0
Share

i followed the code and it works perfectly fine, but my question is as i couldnt understand the code and thus cant manipulate, what would i need to do to stop the game theme music for example wen the user reaches the main game playing level there needs to start a new music so at that particular game level id want that the main game music shall stop playing and this new music starts at the game level. i followed what rimrock suggested, the code of game music and music manager and it works fine, but my concern is that wen id built the game level and at that instance would want the main game music to stop playing and this new music plays in that game level only then what manipulations i would have to make to the code suggested by Rimrock of the game music and music manager script.

avatar image Filipo6 · Dec 26, 2015 at 11:52 PM 0
Share

ATTENTION To everybody who's trying to implement this I suggest taking look at Reder13's answer on this link: [audio-or-music-to-continue-playing-between-scene][1]. It is done within few lines of code. The code above doesn't use singleton at all and did not work for me.

Peace [1]: http://answers.unity3d.com/questions/878382/audio-or-music-to-continue-playing-between-scene.html

avatar image
3

Answer by RodrigoSeVeN · Jun 21, 2012 at 03:17 PM

I looked around for solutions, but none went out to do exactly what we really wanted. Consider you have only one object that can play the music and there will be no copies of it on the other scenes. Activate the Play On Awake and Loop check boxes. Here's my solution in simple JavaScript and I hope t$$anonymous$$s is what you might be looking for.

So, consider you have an object called Jukebox with an AudioSource component in it. It's quite simple, all you need to do is keep track of the current time. Check t$$anonymous$$s:

 var currentMusicTime:float;
 
 function Start(){
    DontDestroyOnLoad(gameObject);
 }
 
 function Update(){
    currentMusicTime=audio.time;
 }
 
 function OnLevelWasLoaded(lvl:int){
    audio.time=currentMusicTime;
 }

I'll post t$$anonymous$$s on other similar threads, I hope it's ok to do so and I hope it helps!

Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Romario07122001 · Jun 07, 2014 at 02:52 PM 0
Share

how to stop the music in scenes that i dont want to play it in

avatar image alxcancado · Jun 13, 2017 at 08:39 PM 0
Share

That's what I was looking for. Actually, I used a combination of PlayerPrefs, Awake() and audio.time. Worked perfectly. Cheer brother.

avatar image
2

Answer by Rimrook · Feb 19, 2010 at 05:00 AM

T$$anonymous$$s is what I have so far, it doesn't seem to work. Instead of comparing audio tracks, it compares names. The surviving gameobject gets renamed to differentiate between the new music manager to the old one.

private static var instance:MusicManager;

public static function GetInstance() : MusicManager { return instance; }

function Awake() { if (instance != null && instance != t$$anonymous$$s) { Destroy(t$$anonymous$$s.gameObject); return; }

   else 
      {
         instance = t$$anonymous$$s;
         var GameMusic : GameObject = GameObject.Find("GameMusic");
         var OldGameMusic : GameObject = GameObject.Find("OldGameMusic");

         If (GameMusic) 
            {            
               Destroy(OldGameMusic);
            }
      }

   t$$anonymous$$s.gameObject.name = "OldGameMusic";
   DontDestroyOnLoad(t$$anonymous$$s.gameObject);

}

@script RequireComponent(AudioSource)

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Statement · Feb 19, 2010 at 10:03 AM 0
Share

Tip: Edit it and clean it up. You're more likely to get people to actually read your code.

avatar image
1

Answer by toddwilliams · Jan 23, 2012 at 02:41 AM

Rimrook left out a vital piece of the continuing music puzzle, an if statement. I believe the second set of code should look like t$$anonymous$$s:

 var NewMusic: AudioClip; //Pick an audio track to play.
 
 function Awake () {
      var go = GameObject.Find("Game Music"); //Finds the game object called Game Music.
      if (go.audio.clip != NewMusic) { 
          go.audio.clip = NewMusic; //Replaces the old audio with the new one set in the inspector.
          go.audio.Play(); //Plays the audio.
      }
 }
Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Hims · Sep 17, 2013 at 12:51 PM 0
Share

@Rimrook : i tried your script....i applied one script in main scene and second script(music manager scene) in all other scenes..it works fine in 4 scenes but it is not working in rest of the scenes..

i have applied audio source in main scene only...haven't applied it on rest of all the scenes. following is the first script.

 private static var instance : musicscript;
 public static function GetInstance() : musicscript {
 return instance;
 }
  
 function Awake() {
     if (instance != null && instance != this) {
         Destroy(this.gameObject);
         return;
     } else {
         instance = this;
     }
     DontDestroyOnLoad(this.gameObject);
 }

here is the second script..

 var NewMusic: AudioClip; //Pick an audio track to play.
  
 function Awake ()
      {
           var go = GameObject.Find("Game Music"); //Finds the game object called Game Music, if it goes by a different name, change this.
           go.audio.clip = NewMusic; //Replaces the old audio with the new one set in the inspector.
           go.audio.Play(); //Plays the audio.
      }

please help..

  • 1
  • 2
  • 3
  • 4
  • ›

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

29 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

The name 'Joystick' does not denote a valid type ('not found') 2 Answers

Audio source in two different scenes 1 Answer

Audio Clip trouble 2 Answers

Scene object scripting 1 Answer

Can I make the signal from Microphone into a 3D sound in real time? 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges