拷贝即用:
单例:
public class SingletonBase<T> where T : class, new()
{
private static T m_instance;
public static T Instance {
get {
if (m_instance == null)
{
// 若T class具有私有构造函数,那么则无法使用SingletonProvider<T>来实例化new T();
m_instance = new T();
}
return m_instance;
}
set { m_instance = value; }
}
}
MonoBehaviour单例:
using UnityEngine;
public abstract class SingletonMonoBehaviour<T> : MonoBehaviour where T : SingletonMonoBehaviour<T>
{
protected static T sInstance = null;
protected static bool IsCreate = false;
public static T Instance
{
get
{
CreateInstance();
return sInstance;
}
}
protected virtual void Awake()
{
if (sInstance == null)
{
sInstance = this as T;
IsCreate = true;
Init();
}
}
public static bool InstanceIsNull()
{
return sInstance == null;
}
protected virtual void Init()
{
}
protected virtual void OnDestroy()
{
sInstance = null;
IsCreate = false;
}
public static void CreateInstance()
{
if (IsCreate)
return;
IsCreate = true;
T[] managers = FindObjectsOfType(typeof(T)) as T[];
if (managers.Length != 0)
{
if (managers.Length == 1)
{
sInstance = managers[0];
sInstance.gameObject.name = typeof(T).Name;
DontDestroyOnLoad(sInstance.gameObject);
return;
}
else
{
foreach (T manager in managers)
{
Destroy(manager.gameObject);
}
}
}
GameObject obj = new GameObject(typeof(T).Name, typeof(T));
sInstance = obj.GetComponent<T>();
DontDestroyOnLoad(sInstance.gameObject);
}
public static void ReleaseInstance()
{
if (sInstance != null)
{
Destroy(sInstance.gameObject);
sInstance = null;
IsCreate = false;
}
}
}