Created
August 3, 2023 00:12
-
-
Save m039/a95be1a6ee59547dfc35eee359854256 to your computer and use it in GitHub Desktop.
Basic Unity singleton
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
public class Singleton<T> : MonoBehaviour where T : Singleton<T> | |
{ | |
static public T s_Instance; | |
static public T Instance | |
{ | |
get | |
{ | |
if (s_Instance == null) | |
{ | |
s_Instance = FindObjectOfType<T>(); | |
} | |
return s_Instance; | |
} | |
} | |
protected virtual void Awake() | |
{ | |
if (s_Instance == null) | |
{ | |
s_Instance = (T)this; | |
Init(); | |
} | |
else | |
{ | |
Destroy(gameObject); | |
} | |
} | |
protected virtual void Init() | |
{ | |
} | |
protected virtual void OnDestroy() | |
{ | |
if (s_Instance == this) | |
{ | |
s_Instance = null; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment