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

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