Created
July 17, 2014 13:15
-
-
Save kleberandrade/7625418d786dbb3f9a45 to your computer and use it in GitHub Desktop.
Singleton genérico criado em C# para Unity 3D
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
using UnityEngine; | |
public class Singleton<T> : MonoBehaviour where T : Component | |
{ | |
private static T instance = null; | |
private static object lockSingleton = new object(); | |
public static T Instance | |
{ | |
get | |
{ | |
if (applicationIsQuitting) | |
return null; | |
lock (lockSingleton) | |
{ | |
if (instance == null) | |
{ | |
instance = (T)FindObjectOfType(typeof(T)); | |
if (FindObjectsOfType(typeof(T)).Length > 1) | |
return instance; | |
if (instance == null) | |
{ | |
GameObject singleton = new GameObject(); | |
instance = singleton.AddComponent<T>(); | |
singleton.name = string.Format("{0}Singleton", typeof(T).ToString()); | |
DontDestroyOnLoad(singleton); | |
} | |
} | |
return instance; | |
} | |
} | |
} | |
void Awake() | |
{ | |
gameObject.name = string.Format("{0}Singleton", typeof(T).ToString()); | |
DontDestroyOnLoad(this); | |
} | |
private static bool applicationIsQuitting = false; | |
public void OnDestroy() | |
{ | |
applicationIsQuitting = true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment