Last active
September 11, 2022 22:18
-
-
Save kalkuz/dc94773299a33ff3472143a2600f6e1b to your computer and use it in GitHub Desktop.
Singleton MonoBehaviour class template which helps to build over when you need Singletons in Unity.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
[DisallowMultipleComponent] | |
public class SingletonMonoBehaviour : MonoBehaviour | |
{ | |
private static SingletonMonoBehaviour m_instance; | |
public static SingletonMonoBehaviour Instance | |
{ | |
get | |
{ | |
if (m_instance == null) | |
{ | |
var go = new GameObject(nameof(SingletonMonoBehaviour)); | |
var comp = go.AddComponent<SingletonMonoBehaviour>(); | |
m_instance = comp; | |
} | |
return m_instance; | |
} | |
} | |
private void EnsureSingleExistence() | |
{ | |
if (m_instance != null) | |
{ | |
if (m_instance == this) return; | |
Destroy(this); | |
return; | |
} | |
m_instance = this; | |
} | |
private void Awake() | |
{ | |
EnsureSingleExistence(); | |
} | |
private void OnEnable() | |
{ | |
EnsureSingleExistence(); | |
} | |
private void OnDestroy() | |
{ | |
if (m_instance == this) | |
{ | |
m_instance = null; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment