Wanzyee Studio

Base class to implement the singleton pattern for UnityEngine.MonoBehaviour. More...

Inherits MonoBehaviour.

Static Public Attributes

static T instance => Singleton<T>.instance
 Get the singleton instance. More...
 

Protected Member Functions

 BaseSingleton ()
 Constructor to check inheritance, since we can't constraint subclass. More...
 
virtual void Awake ()
 Awake, check and handle duplicated instances. More...
 

Static Protected Attributes

static bool autoDestroy
 Flag if to destroy excess instance automatically when it Awake(). More...
 

Detailed Description

Base class to implement the singleton pattern for UnityEngine.MonoBehaviour.

This works with Singleton to minimize coding, if you don't need custom inheritance. Derive from this to make a UnityEngine.MonoBehaviour singleton. Only allow the class of current singleton to derive, otherwise throw an exception if in the editor. This applies the singleton's root Object.DontDestroyOnLoad() and handle duplicates when Awake().

Example to implement singleton, just derive from this:

public class SomeComp : BaseSingleton<SomeComp>{}

Example to access from another class:

public class AnotherClass{
private void DoSomething() => Debug.Log(SomeComp.instance);
}
Template Parameters
TThe component type.
Type Constraints
T :BaseSingleton<T> 

Constructor & Destructor Documentation

BaseSingleton ( )
protected

Constructor to check inheritance, since we can't constraint subclass.

Member Function Documentation

virtual void Awake ( )
protectedvirtual

Awake, check and handle duplicated instances.

Apply Object.DontDestroyOnLoad() to the root if this's the singleton. Otherwise check if autoDestroy to suicide or log error. Call base.Awake() if you implement Awake() in the subclass.

Reimplemented in FramerateCounter.

Member Data Documentation

bool autoDestroy
staticprotected

Flag if to destroy excess instance automatically when it Awake().

T instance => Singleton<T>.instance
static

Get the singleton instance.