Created
August 26, 2016 10:39
-
-
Save leducanhh/885e3f694c06aeb166a8749ea0b20198 to your computer and use it in GitHub Desktop.
[Unity] Singleton Pattern
This file contains hidden or 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 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