Singleton and MonoBehaviour in Editor

Hello all,

I’m using a simple singleton pattern in a script:

public class EasySingleton {
  private static EasySingleton instance = null;
  public static EasySingleton Instance { get { return instance; } }

  void Awake() {
    instance = this;
  }
}

Everything in-game works fine, but there is one annoying thing when working in the editor: if I press Play, make some code changes, and click back in the game view, I get NullReferenceExceptions when accessing “instance”. Normally, such on-the-fly code editing works fine.

So my questions are: what events get called when switching from play mode to code and back without stopping the game before? How can I optimize such a singleton pattern to work smoothly in the editor? Does this work better with another singleton pattern?

Best regards,
Felix

1 Answer

1

Yep, usually i use this one:

private static EasySingleton instance = null;
public static EasySingleton Instance
{
    get
    {
        if (instance == null)
            instance = (EasySingleton)FindObjectOfType(typeof(EasySingleton));
        return instance;
    }
}

To be on the absolute safe side you could implement a second check to create it if it’s not found

get
{
    if (instance == null)
    {
        instance = (EasySingleton)FindObjectOfType(typeof(EasySingleton));
        if (instance == null)
            instance = (new GameObject("EasySingleton")).AddComponent<EasySingleton>();
    }
    return instance;
}

The problem is that when you change something during runtime Unity recompiles all scripts and therefore have to recreate every object instance. Unity uses it's own internally serialisation function to "save" the old state and to restore it after the objects are recreated. But Unity doesn't serialize everything so you will loose all non serialized fields. As long as you only use serialized fields (public or [SerializeField]) it should be ok.

–

Yep, thats what I currently do - check if the singleton != null. Double-checking and creating if not existant is a nice idea, thanks.

–

Thanks Bunny83 this saved my life!

–

Double checked locking is a BAD idea : http://stackoverflow.com/questions/394898/double-checked-locking-in-net Instead, the simplest and best approach is: https://msdn.microsoft.com/en-us/library/ff650316.aspx

–

1. You DO use double checked locking - check your second example with a nest if/null check. 2. That is false, check out the glut of threading libs on AS. 3. New is actually used with many objects, not the least of which is the most common of all - GameObject. 4. The singleton pattern applies to a memory state - not persistence, I recommend reading GoF for a nice background on it. 5. Perhaps - but in all honesty I believe the MM has been updated since DCL was "bad" so it seems to be in vogue again anyhow.

–