I have an audio that is set to DontDestroyOnLoad() but I want it to destroy on certain scenes, is it possible to check that and make the audio only DontDestroyOnLoad() if it is a certain scene?
Here is my script currently:
using UnityEngine;
using System.Collections;
public class dialogueclassicexist : MonoBehaviour {
void Awake() {
DontDestroyOnLoad(gameObject);
}
}
Awake is only called once, when the behavior is loaded, therefore it is not checking every scene because you are not loading a new one every scene. Try something like this.
using System.Collections;
public class AudioGSingle : MonoBehaviour {
private static AudioGSingle instance = null;
public static AudioGSingle Instance {
get { return instance; }
}
void Awake() {
if (instance != null && instance != this) {
Destroy(this.gameObject);
return;
} else {
instance = this;
}
DontDestroyOnLoad(this.gameObject);
}
void OnLevelWasLoaded(int lvlNum){
if(Application.loadedLevelName == "gameover"){
Destroy(this.gameObject);
}
}
}
Use the properties Application.loadedLevelName for String or Application.loadedLevel for int index.
if( Application.loadedLevelName == "MyScene")
DontDestroyOnLoad(gameObject);
theLucre is completely right with his answer, however you can also make use of the inbuild function:
void OnLevelWasLoaded(int level)
{
if(level == 123) // the scene number
{
// Do something
}
}
OnLevelWasLoaded() is automatically called whenever (take a guess) a level is loaded! (Suprise!)
Hope this helps~
Cerbi