Skip to content

Instantly share code, notes, and snippets.

@leducanhh
Created August 26, 2016 10:39
Show Gist options
  • Save leducanhh/885e3f694c06aeb166a8749ea0b20198 to your computer and use it in GitHub Desktop.
Save leducanhh/885e3f694c06aeb166a8749ea0b20198 to your computer and use it in GitHub Desktop.
[Unity] Singleton Pattern
public class GenericSingletonClass<T> : MonoBehaviour where T : Component
{
private static T instance;
public static T Instance {
get {
if (instance == null) {
instance = FindObjectOfType<T> ();
if (instance == null) {
GameObject obj = new GameObject ();
obj.name = typeof(T).Name;
instance = obj.AddComponent<T>();
}
}
return instance;
}
}
public virtual void Awake ()
{
if (instance == null) {
instance = this as T;
DontDestroyOnLoad (this.gameObject);
} else {
Destroy (gameObject);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment