Don't reload the AudioSource when back to scene
Simple question but make me blur.
I have an audio source on let say "Main" scene, and I make it DontDestroyOnLoad, which make it could keep playing my audio even i going next scene, let say "Game" scene.
Problem is, when i get back from "Game" scene to "Main" scene, my audio will restart over but not continue playing as i expected. How should i actually script for this?
My current script :
void Awake() { if (instance != null && instance != this) { Destroy(this.gameObject); return; } else { instance = this; } DontDestroyOnLoad(this.gameObject); }
Answer by v01pe_ · Aug 23, 2016 at 09:13 AM
I guess the problem here is that when you load the scene again, this
will never be the same as instance
, because it's technically speaking a different object. Also the object that's kept loaded will not receive the Awake()
call!
I would try it like this:
static Object instance = null;
void Awake()
{
if (instance != null)
{
Destroy (this.gameObject);
return;
}
else
{
instance = this;
DontDestroyOnLoad (this.gameObject);
}
}
void OnDestroy()
{
if (instance == this)
{
instance = null;
}
}
I still get the same result, when get back to the $$anonymous$$ain scene, the music still start from very beginning but not continue as where it play.
I tried this quickly in a new project, and it worked as excepted! How do you play the AudioSource and is the script you wrote attached to the same object?
yes, this script i attach with the same AudioSource object.
void Start()
{
mySource = GetComponent<AudioSource> ();
instance = this;
}
is this affect?
Your answer
Follow this Question
Related Questions
Second AudioClip won't play 0 Answers
How to stop current audio before another audio starts? 0 Answers
How to reduce delay when playing sound 0 Answers
Some sounds won't play 0 Answers
Newbie with OnTriggerEnter & Audio Files 0 Answers