Tutorial by Examples

Since Unity 5.2.5 it's possible to use RuntimeInitializeOnLoadMethodAttribute to execute initialization logic bypassing MonoBehaviour order of execution. It provides a way to create more clean and robust implementation: using UnityEngine; sealed class GameDirector : MonoBehaviour { // Beca...
In this example, a private static instance of the class is declared at its beginning. The value of a static field is shared between instances, so if a new instance of this class gets created the if will find a reference to the first Singleton object, destroying the new instance (or its game object)...
This example combines multiple variants of MonoBehaviour singletons found on the internet into one and let you change its behavior depending on global static fields. This example was tested using Unity 5. To use this singleton, all you need to do is extend it as follows: public class MySingleton ...
In projects that feature several singleton classes (as is often the case), it can be clean and convenient to abstract the singleton behaviour to a base class: using UnityEngine; using System.Collections.Generic; using System; public abstract class MonoBehaviourSingleton<T> : MonoBehaviou...
The core idea is to use GameObjects to represent singletons, which has multiple advantages: Keeps complexity to a minimum but supports concepts like dependency injection Singletons have a normal Unity lifecycle as part of the Entity-Component system Singletons can be lazy loaded and cached loca...
Most Singleton examples use MonoBehaviour as the base class. The main disadvantage is that this Singleton class only lives during run time. This has some drawbacks: There is no way of directly editing the singleton fields other than changing the code. No way to store a reference to other assets...

Page 1 of 1