Created
January 1, 2022 22:46
-
-
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
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 : 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