- Home /
How can I check the scene and play audio accordingly?
So currently I have a SoundManager that persists between scenes and plays audio for them. I want a specific level to play a different track though. What happens is, if I go from the previous level to that level, the audio won't work. It will just stay what the previous audio was. On the other hand though, if I start with that level initially, it will play the correct audio. Here's what the script looks likes.
public class SoundManager : MonoBehaviour {
public AudioSource deathAudio;
public AudioSource musicSource;
public AudioSource bossAudio;
public static SoundManager instance = null;
void Awake ()
{
if (instance == null)
instance = this;
else if (instance != this)
Destroy(gameObject);
DontDestroyOnLoad(gameObject);
if (SceneManager.GetActiveScene().name == "Level10") // this is correctly checking for the scene.
{
musicSource.Stop();
bossAudio.Play();
}
}
public void PlaySingle(AudioClip clip)
{
deathAudio.clip = clip;
deathAudio.Play();
}
And here it is in the inspector if it helps. http://puu.sh/paHDl/768333c4ee.png
I tried putting the if-test in Awake(), Start(), Update() and nothing seems to accurately check it.
Answer by Alec-Slayden · May 31, 2016 at 11:21 PM
Awake and Start are only called once for the lifetime of the object. This means if it isn't getting destroyed between scenes, that lifetime persists and they won't be called again.
In Update it was probably constantly being called, which would prevent it from playing appropriately.
OnLevelWasLoaded () is probably the better method to use in this case, or if you use 5.4, utilize SceneManager.sceneLoaded.
if you prefer to use Update, you can instead check if the new music AudioSource is playing, and only call Play if that is false. I advise using a single call method, however, such as OnLevelWasLoaded.