- Home /
Avoid NullReferenceException with Singleton
I'm using a game singleton to store variables accross scenes, such as player score.
When I'm testing my various scenes I get a NullReferenceException for variables which are held in the singleton becuase the singleton is being made static in the first scene.
static var instance : GameManager; // identifies this script as a global item
Is there a way that I can make each scene load the singleton while testing, but prevent each scene from making an instance of it at runtime?
Answer by andeeee · Apr 21, 2010 at 04:10 PM
You can mark the object with DontDestroyOnLoad to prevent it from being destroyed during a scene change. However, you should check for the object's existence before doing this so that you don't end up with multiple copies. You could do this by trying to find the object before instantiating it:-
if (GameObject.Find("SingletonObject") == null) {
var sng = Instantiate(Resources.Load("Singleton"));
sng.name = "SingletonObject";
DontDestroyOnLoad(sng);
}
I already have a DontDestroyOnLoad on the Singleton. So would simply checking for the Singleton object's existence and then if not found instantiating it work? e.g.
if (GameObject.Find("SingletonObject") == null) { var sng = Instantiate(Resources.Load("Singleton")); sng.name = "SingletonObject"; }
Ok, pasting code doesn't work in comments.
All I did was remove the line DontDestroyOnLoad(sng);
Because there is already a DontDestroyOnLoad on the Singleton script. Works for my needs, thanks
Oddly, $$anonymous$$y use of the singleton started causing Unity to crash on the scene that was parsing it. I changed all the variables that I was using in the singleton to static as Duck suggested.
Whenever on of the static vars changes it updates to playerprefs to be stored whenever a certain variable needed later in another scene.
Answer by duck · Apr 21, 2010 at 04:11 PM
You're probably getting null reference exceptions because your singleton variables contain references to objects which were destroyed when the new level was loaded.
Rather than re-loading the singleton each time a scene is loaded, you should use DontDestroyOnLoad to preserve your object throughout all scenes, or - if you are only storing data in variables - simply just use static variables, and don't create a singleton instance of your class at all.
Answer by Cyclops · Apr 21, 2010 at 05:50 PM
I have a demo in the Forums that might be useful, Demo of a (singleton) LevelManager.