Skip to content

Instantly share code, notes, and snippets.

@nailuj05
Created January 1, 2022 22:46
Show Gist options
  • Save nailuj05/db18aa10bcc0915e6aa5a6b0f87b2d24 to your computer and use it in GitHub Desktop.
Save nailuj05/db18aa10bcc0915e6aa5a6b0f87b2d24 to your computer and use it in GitHub Desktop.
Clean Unity Singleton Implementation. Inherit from Singleton<ExampleClass> to use it. Access the Singleton using ExampleClass.main
public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
private static T instance;
public static T main
{
get
{
if (instance == null)
instance = FindObjectOfType<T>();
if (instance == null)
Debug.Log($"No object of type {typeof(T).ToString()} found.");
return instance;
}
}
protected void OnEnable()
{
if (instance == null)
instance = this as T;
if (instance != this)
DestroyMe();
}
void DestroyMe()
{
if (Application.isPlaying)
Destroy(this);
else
DestroyImmediate(this);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment