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?

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";

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.

I have a demo in the Forums that might be useful, Demo of a (singleton) LevelManager.