Skip to content

Instantly share code, notes, and snippets.

@allxrise
Created August 14, 2022 00:36
Show Gist options
  • Save allxrise/aa5ad8bad82d5780727b439a17a03f8f to your computer and use it in GitHub Desktop.
Save allxrise/aa5ad8bad82d5780727b439a17a03f8f to your computer and use it in GitHub Desktop.
Singleton utility file for Unity from Tarodev ( https://www.youtube.com/watch?v=tE1qH8OxO2Y&t=229s )
using UnityEngine;
public abstract class StaticInstance<T> : MonoBehaviour where T : MonoBehaviour
{
public static T Instance { get; private set; }
protected virtual void Awake() => Instance = this as T;
protected void OnApplicationQuit()
{
Instance = null;
Destroy(gameObject);
}
}
public abstract class Singleton<T> : StaticInstance<T> where T : MonoBehaviour
{
protected override void Awake()
{
if (Instance != null) Destroy(gameObject);
base.Awake();
}
}
public abstract class PersistentSingleton<T> : Singleton<T> where T : MonoBehaviour
{
protected override void Awake()
{
base.Awake();
DontDestroyOnLoad(gameObject);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment