Skip to content

Instantly share code, notes, and snippets.

@kleberandrade
Created July 17, 2014 13:15
Show Gist options
  • Save kleberandrade/7625418d786dbb3f9a45 to your computer and use it in GitHub Desktop.
Save kleberandrade/7625418d786dbb3f9a45 to your computer and use it in GitHub Desktop.
Singleton genérico criado em C# para Unity 3D
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