I have a singleton script that is a component of a placed object in a scene. After I load a second scene (via Application.LoadLevel), I’m somehow still able to call a function of the singleton, even though the debugger tells
me that the singleton instance is null.
Shouldn’t I be getting a null reference exception? Is the script, or the game object of which it is a component, somehow sticking around after the scene is unloaded? Any pointers on where to start looking would be appreciated!
The singleton is implemented like so (lots of code snipped):
public class Global : MonoBehaviour {
private static Global instance;
public static Global Instance {
get { return instance; }
}
void Awake() {
instance = this;
}
}
After the object with the singleton script has supposedly been unloaded, I call the singleton’s function like this:
if ( GUI.Button( new Rect( x, y, width, height ), "Save and Quit" ) ) {
if ( Global.Instance == null ) {
print( "Global.Instance == null" ); // <--this is being printed
} else {
print( "Global.Instance != null" );
}
Global.Instance.MainMenu(); // <--this function is still getting called
}
Some notes on what I’ve already investigated:
-
The object which has this singleton script component is not in the second scene, nor is it preserved via DontDestroyOnLoad.
-
I confirmed that the singleton script is receiving an OnDestroy callback when the new scene is loaded.
-
I’ve placed breakpoints in the singleton’s Awake call to make sure that it wasn’t somehow getting instantiated multiple times.
-
If I load the second scene directly (not having gone through the first scene beforehand), I do get the null reference exception as I would expect. This seems to suggest that something is sticking around…
-
I’m somehow able to access a public member variable of the singleton class, after the singleton is supposedly destroyed. This particular variable is null until the singleton’s Start function sets it. However, it is non-null when I am attempting to access it after the scene is supposedly unloaded.