Simple MonoBehaviour Singleton

There is a simplest implementation of MonoBehaviour Singleton like this:

using UnityEngine;

public class GameManager : MonoBehaviour
{
    public static GameManager Instance { get; private set; }

    void Awake()
    {
        if(Instance != null && instance != this)
        {
            Destroy(gameObject);
            return;
        }
        Instance = this;
        DontDestroyOnLoad(gameObject);
    }
}

but I don’t understand the && instance != this check; I think it’s completely unnecessary. There are three cases:

  1. == null, the first instance.
  2. != null AND != this, a second instance, destroy itself automatically.
  3. != null AND == this, the Awake of the first instance is executed again? this is impossible.

If it is indeed necessary, can you provide a proof?

I mean, the ‘simple’ singleton monobehaviour you see there is also what’s known as a ‘defective’ singleton. So how it works is kinda irrelevant. It’s not a singleton pattern you should use.

In short, if you have to place a singleton in a scene, then it’s not a very effective singleton. An effective singleton should be able to be called from just about any context, at any time.

The simple, and also effective, monobehaviour singletons should construct themselves on demand, or load themselves out of Resources/Addressables.

That way you both:

  • Don’t need to ever place them in a scene
  • Ensure they are always accessible immediately, even when loading into playmode

But I would only look to use a monobehaviour singleton if you absolutely need monobehaviour only things. Such as Update(), etc. Otherwise, other options such a static class or even scriptable objects can do a better job under more contexts.

And queue the usual back and forth argy bargy about singletons. OP, prepare for your thread to be derailed quickly.

I’m not sure where you found this implementation, but it’s a poor example of a singleton.

There are several issues with it. For instance, the Awake or OnEnable method of another script might execute first, as the order is not guaranteed between scripts and may change with each build or Unity version upgrade, calling the Instance property which will be null and unavailable at that point. Additionally, since the Destroy method removes MonoBehaviours at the end of the frame, there can be a frame where multiple singleton instances exist, something that should never happen.

There are other problems as well, and you can find plenty of discussions on the forums about what we refer to as “defective” singletons.

For a proper singleton implementation, I recommend reading Kurt’s post here: SceneManager Singleton Null Error on Awake - Multiple ASSERT ERRORs in Release Build - #7 by Kurt-Dekker

When you disable “Domain Reload” (to enter the play mode faster), static variables will not be reset automatically.

What I haven’t tested yet is if MonoBehaviour references persist when DomainReload and SceneReload are disabled to get faster into play mode. Since the scene isn’t reloaded and the static variable persists, case 3 ( != null AND == this) could occur, maybe.
But only in this specific setup, in the editor, with fast enter play mode options turned on.

NOTES:

Usually you would write a private static void method with an RuntimeInitializeOnLoadMethod Attribute where you manually reset your static variables.

This is also useful when you go to your main menu and back into the game scene, because there you have the exact same problem (static variables persist) and if you then have your custom reset-methods, you can just call them with reflection (or manually).

DontDestroyOnLoad(gameObject); is really bad tho, if you want to use a Singleton like that, you should remove that line. If you have your Menu Scene and your Game Scene and you have an Enemy Manager Singleton in your Game Scene - why the hell would you want this object to persist when you load your menu scene again?! Or any other scene really - if you need that enemy manager in another level as well, spawn a new one. Or put it in an additional scene that you load additive because that’s what DontDestroyOnLoad does as well, but then you have control over the lifecycle of the object by controlling the lifecycle of the scene.

Also if you want to use the code you posted (which I wouldn’t recommend, it’s better to at least call FindAnyObjectByType<GameManager>() in the getter), you should add your script to the start of the execution order, just drag and drop it there.

And last tip: do not call anything “GameManager”. Make a GameStateController or whatever, be more precise if you don’t want to end up with unmaintainable spaghetti-code.

The role of a singleton is essentially:

  • On the first call, it creates itself (lazy initialization).
  • On subsequent calls, it returns the existing instance.

It doesn’t really matter how that behavior is implemented. The code you provided contains an error, and destroying the singleton instance doesn’t make sense Instance will always refer to the same object.

In general, you also don’t want MonoBehaviour classes to act as singletons.

I would suggest taking a look into DI (Dependency Injection) now or in the future: https://github.com/modesttree/Zenject

This is the actual answer to OP’s question:

Simple test case is this:

public class TestScript : MonoBehaviour
{
    private static TestScript instance;
    private void Awake()
    {
        Debug.Log(instance == this);
        instance = this;
    }
}

Turn off assembly reload and scene reload, and enter playmode twice. The first time it will print false, the second true, as the static variable hasn’t been cleared and the scene hasn’t been reloaded so it’s the same object instance that gets Awake called on it.

But yeah, other than that, don’t actually implement singletons like this - have them self-initialize on demand or on game startup, depending on what works best for your loading.
If you need them to run per-frame code, the PlayerLoop saves you from needing a MonoBehaviour or something that lives in the scene at all, but it’s a bit more advanced, so depending in what you’re comfortable with it can be skipped.

In addition to the above, if you want to run per-frame code as an alternative to the PlayerLoop, you can use Unity - Scripting API: Awaitable.NextFrameAsync inside a while loop. The Awaitable API is particularly useful because it lets you execute game loop logic from a regular C# class instead of relying on a MonoBehaviour, so it’s worth checking out.

It makes sense if you’re trying to implement the Singleton pattern. The Singleton pattern should ensure that only a single instance of the class can ever be created during the lifetime of the application. If a second instance was to be created when some scene is loaded again, it could lead to two clients in the project holding references to different instances of the same class (remember that anything can grab a reference to the singleton object from anywhere at anytime).

I’ve also seen some people use singletons like this by adding the same prefab to every one of their scenes, containing the same set of singleton managers. The idea being that you can then enter Play Mode from any scene, and all the managers will already be available. And if you transition to a different scene, all the managers from the first scene will follow you to the second scene, and the managers from the loaded scene are destroyed. This makes it possible to e.g. have an AudioManager continue playing audio throughout the transition.

There’s a risk with this approach: unless you’re careful, it can lead to FindAnyObjectByType getting executed many times when existing Play Mode / quitting the application, which can increase loading times unnecessarily.

I remember in one one of the first projects I ever worked on it took multiple seconds to exist Play Mode, and eventually we realized it was because of FindObjectOfType being used in the getters of all our singletons :man_facepalming:t3:

Let me leave a link here: https://www.youtube.com/watch?v=LFOXge7Ak3E

I recommend watching this and using the basic structure as your guide. I’ve been using a slightly customized version since I encountered the tutorial.

I mean this works if you don’t disable domain reload (I never need to), it depends on scene management (why have more than 1!).
You can over think it or go with what works. It may not be a perfect Singleton but maybe you want to reference things in the scene - it works as a ‘static instance’.

The Singleton<T> and PersistentSingleton<T> implementations in the video suffer from the same problem of FindAnyObjectByType and (in this case new GameObject + AddComponent as well) potentially getting spammed a lot when exiting Play Mode that I described above. It’s not a safe Singleton implementation, because multiple instances of each type actually can get created during a single application run very easily. For example, if you ever create a singleton object that saves some state related to the ongoing session during its unloading, you could end up losing all that data if a new instance ends up getting created by some random client during unloading.

RegulatorSingleton<T> is not even trying to be a singleton - it is by design meant to destroy and instantiate multiple instances of the same type during every session. Yet from all the clients’ point of view it looks like any regular singleton - all they see is a static Instance property, but little do they know that the instance they can acquire through it could get destroyed at any point in time.

If you do want to go the route of providing global access to an instance that can get destroyed and replaced with a different one at anytime, then I think it’s a good idea to at least design the API around the fact that the instance can change at any time, by providing an InstanceChanged event, at a minimum.

Gosh another Singleton thread. I will suggest that one should just about never use an inferior implementation if a superior implementation is safe, more reliable and just as easy to implement.

I “never” type the Singleton syntax any more. I bury the brains of such operations knowing that it will work.

I guess I’m not disputing that there may be better ways. I’m certain the Git-Amend Discord would be happy to hear about it (seriously) and might modify their approach as a result.

I suppose I’m mostly astonished that there isn’t a single posted example that just handles “a published pattern” safely and efficiently.

What other patterns have generated dozens of unsafe examples over the years?

I believe the main reason we see so many singleton-related threads is because of YouTube tutorials that many developers rely on, which often provide poor advice. The singleton implementations shown in these tutorials are usually tested only in small projects, single-scene setups or ones with few interacting components.

These tutorials tend to use a “defective singleton” as a shortcut for handling references, which was never the purpose of the singleton pattern. Reference management can be handled just as easily with a static instance reference. The true purpose of a singleton is to guarantee that exactly one instance of an object exists at any time (not zero, not more than one). These flawed implementations fail to do that, which is why so many threads report issues with singletons during scene changes or builds.

A good example of this problem is the topic linked above regarding Kurt’s implementation.

Kurt’s version is a proper, safe singleton. I recommend using it or at least studying it, to understand the issues it solves and apply this approach to any project that needs a singleton implementation.

There’s also the fact that the Singleton pattern, which would typically be trivial to implement, just does become much more complicated to implement in a reliable manner when you introduce Unity’s GameObject architecture into the mix.

Unity’s architecture is built so much around the idea that any components can be freely attached to any GameObjects at any time, and any components can be freely destroyed at anytime, that creating a system that tries to ensure that exactly one instance will always exist becomes quite messy.

Also, just simply doing new GameObject().AddComponent<T>() would rarely be enough, because when working with MonoBehaviours, you typically want to be able to configure them using the Inspector in Edit Mode. And then this opens the question about what is the best way to acquire a reference to that pre-configured object. Do you use Resources, and live with the fact that all singletons will always be included in builds, even if not used by anything? Do you use Addressables, and live with the fact that you can’t (safely) load them synchronously? Do you use FindAnyObjectByType and live with the fact that you might now always need to start the game from the same preload scene?

Then there are a bunch of tricky edge cases, like how to handle situations where the singleton is destroyed when quitting the application, or what to do if a singleton component is attached to a child GameObject and can’t be targeted by DontDestroyOnLoad, etc.

Thanks, that’s true, I’ve tested it too.

The “Domain Reload” option is a bit hard to find, it took me a while to find it. Its path is: Editor > Project Settings > Editor > Enter Play Mode Settings > When entering Play Mode.

In the code I posted, there’s another issue, that is when instance == this,

Instance = this;
DontDestroyOnLoad(gameObject);

will be executed again.

In conclusion, I can make the following changes:

In the case of “Reload Domain”, it looks like this:

using UnityEngine;

public class GameManager : MonoBehaviour
{
    public static GameManager Instance { get; private set; }

    void Awake()
    {
        if(Instance != null)
        {
            Destroy(gameObject);
            return;
        }
        Instance = this;
        DontDestroyOnLoad(gameObject);
    }
}

And in the case of “Do not reload Domain”, it becomes:

using UnityEngine;

public class GameManager : MonoBehaviour
{
    public static GameManager Instance { get; private set; }

    void Awake()
    {
        if (Instance != null)
        {
            if (Instance != this)
            {
                Destroy(gameObject);
                return;
            }
            return;
        }
        Instance = this;
        DontDestroyOnLoad(gameObject);
    }
}

Of course, the latter can also be used for “Reload Domain”, but a bit redundant.

I recommend preferring implementations that are logically clearly always guaranteed to work, over ones that only work as long as everybody in your team remembers not to do X, Y or Z. Less mental overhead from day one, and less risk of bugs in the long term.

During the first couple of years of programming, it’s easy to start obsessing a lot over the smallest of implementation details, such as line count, or if some cheap if-check could be omitted in practice in a code path that is only executed very rarely.

As you get more years under your belt you tend to zoom out more, and realize that the exact implementation details of some method that you rarely need to read and modify don’t usually matter that much. The thing that you should really be investing 90% of your design efforts towards is the public APIs that your types expose to the outside world:

public class Game
{
	/// <summary>
	/// Returns a globally shared instance of the Game class.
	/// </summary>
	/// <remarks>
	/// <para>
	/// This is guaranteed to always return the same instance of the Game class throughout the application lifecycle.
	/// </para>
	/// <para>
	/// Returned instance will never be null, but can be destroyed after the application has started quitting.
	/// </para>
	/// </remarks>
	public static Game Instance { get; }
}

This is the thing that potentially many clients across your codebase can end up interacting with, so this is what has the biggest impact on the overall reliability, readability, maintainability and flexibility of your codebase.

Of course it’s a good idea to take the time to fully understand the reason behind each little line of code that you add to your codebase - even if it’s only for your personal growth as a programmer - but also remember not to miss the forest from the trees :grin:

You’re absolutely right. We should carefully consider the details, but we can’t ignore the big picture either; sometimes, it really does require making decisions and trade-offs.