Created
August 14, 2022 00:36
-
-
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 )
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; | |
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