Skip to content

Instantly share code, notes, and snippets.

@m039
Created August 3, 2023 00:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save m039/a95be1a6ee59547dfc35eee359854256 to your computer and use it in GitHub Desktop.
Save m039/a95be1a6ee59547dfc35eee359854256 to your computer and use it in GitHub Desktop.
Basic Unity singleton
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