SingleTon
MonoBehaviour Singleton.
public class MonoBehaviourSingleton<T> : MonoBehaviour where T: MonoBehaviour {
protected bool isDonDestroy = false;
void Awake()
{
if (isDonDestroy)
{
DontDestroyOnLoad(this.gameObject);
}
}
private static T instance;
public static T Instance
{
get
{
if (instance == null)
{
T[] objs = FindObjectsOfType<T>();
if (objs.Length > 0)
{
instance = objs[0];
}
if (instance == null)
{
string name = typeof(T).ToString();
GameObject go = GameObject.Find(name);
if (go == null)
{
go = new GameObject(name);
}
instance = go.AddComponent<T>();
}
}
return instance;
}
}
}
Class Singleton
Reflection을 통해 생성자 확인.
public class Singleton<T> where T: class {
private static T instance = null;
public static T Instance
{
get
{
if (instance == null)
{
Type t = typeof(T);
ConstructorInfo[] ctors = t.GetConstructors();
if (ctors.Length > 0) // if there are public constructors, it's error.
{
throw new InvalidOperationException(string.Format("Error : Have public constructor"));
}
instance = (T)Activator.CreateInstance(t, true);
}
return instance;
}
}
}