- Home /
Question by
Yoseki · Jun 20, 2014 at 05:07 PM ·
musicdontdestroyonload
Audio source to be played across all scenes without being destroyed?!?
Hello. I was wondering what is wrong with my script. I have attached it to the camera and made an audio source there:
var song : AudioSource;
function Awake () {
if (!audio.isPlaying){
audio.Play();
}
else if(audio.isPlaying){
DontDestroyOnLoad (AudioSource);
}
}
function Update () {
if (!audio.isPlaying){
DontDestroyOnLoad (AudioSource);
audio.Play();
}
}
Thank you :D in advance :D
Comment
Best Answer
Answer by fafase · Jun 20, 2014 at 06:21 PM
It seems your DontDestroyOnLoad is done on a type and not an object.
DontDestroyOnLoad(AudioSource); <- AudioSource is a type
As you attach it to the camera, here is something you can try:
static var instance : ScriptName; // Declare a static variable of the script type
function Awake(){
if(instance == null){ // If the static var is null
instance = this; // assign the script to it
DontDestroyOnLoad(gameObject); // Keep the script over scene loadings
}else if(instance != this){ // if the variable is not this script
Destroy(gameObject); // Destroy the object
}
}
This is a singleton pattern, it means you are keeping your object alive over different scenes but also prevent that when coming back, you don't get a second creation of the object.