I created a repository for using singleton’s with MonoBehaviours. I welcome any feedback. I used reflection and I have quite a few recommendations for improvements (listed on my GitHub, too).
All you have to do is add one MonoBehaviour to the scene, and all defined Singleton’s in code will be instantiated automatically. Singletons can be conditionally instantiated and destroyed by defining a static property.
Personally I hate this pattern, and unfortunately it is the most-common pattern people reach for. I don’t want to be obligated to remember to drop crap into my scene(s). Sure, works fine when that crap is 1 manager, but when it is 27 managers, it’s a nightmare to manage and remember. I can’t count how many bugs arise from this messy approach.
Instead, I always use this pattern:
Simple Singleton (UnitySingleton):
Some super-simple Singleton examples to take and modify:
Simple Unity3D Singleton (no predefined data):
Unity3D Singleton with a Prefab (or a ScriptableObject) used for predefined data:
These are pure-code solutions, do not put anything into any scene, just access it via .Instance!
If it is a GameManager, when the game is over, make a function in that singleton that Destroys itself so the next time you access it you get a fresh one, something like:
public void DestroyThyself()
{
Destroy(gameObject);
Instance = null; // because destroy doesn't happen until end of frame
}