- Home /
How to check scene number and use it in an If statement?
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);
}
}
Answer by msnyder102 · Dec 09, 2014 at 05:00 AM
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);
}
}
}
if(Application.loadedLevelName == "gameover")
{
Destroy(this.gameObject);
}
Works for me, thanks!
Answer by theLucre · Dec 09, 2014 at 02:23 AM
Use the properties Application.loadedLevelName for String or Application.loadedLevel for int index.
http://docs.unity3d.com/ScriptReference/Application-loadedLevelName.html http://docs.unity3d.com/ScriptReference/Application-loadedLevel.html
if( Application.loadedLevelName == "MyScene")
DontDestroyOnLoad(gameObject);
I tried your script and it doesn't seem to work, although I get no error messages. I currently have this script:
using UnityEngine;
using System.Collections;
public class audiolevel1 : $$anonymous$$onoBehaviour {
// Use this for initialization
void Start () {
if (Application.loadedLevelName == "hiding1")
DontDestroyOnLoad (gameObject);
}
}
Answer by Cerbion_ · Dec 09, 2014 at 02:48 AM
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
Unfortunately, neither seem to be working. :( Currently, I'm trying to make it so that it destroys only on the gameover scene. Here is my current script:
using System.Collections;
public class AudioGSingle : $$anonymous$$onoBehaviour {
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;
}
if( Application.loadedLevelName == "Ghost"){
DontDestroyOnLoad(this.gameObject);
}
if( Application.loadedLevelName == "gameover"){
Destroy(this.gameObject);
}
}
}