Skip to content

Instantly share code, notes, and snippets.

@kalkuz
Last active September 11, 2022 22:18
Show Gist options
  • Save kalkuz/dc94773299a33ff3472143a2600f6e1b to your computer and use it in GitHub Desktop.
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.
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