Unity中常用的两种单例
文章目录
1、继承class的单例(继承改类的单例必须要有一个私有的无参构造函数)
public abstract class Singleton<T> where T : Singleton<T>
{
protected static T _instance;
protected static object _lock = new object();
public static T Instance
{
get
{
lock (_lock)
{
if (_instance == null)
{
//获得T类型的无参的私有构造函数
var constructors = typeof(T).GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic);
var constructor = Array.Find(constructors , c => c.GetParameters().Length == 0);
if (constructor == null)
throw new Exception(string.Format("没有找到类型:{0}的无参私有构造函数!",typeof(T).ToString()));
_instance = constructor.Invoke(null) as T;
}
return _instance;
}
}
}
}2、继承Monobehavior的单例
public abstract class MonoSingleton<T> : MonoBehaviour
where T : MonoSingleton<T>
{
protected static T _insatnce;
protected static object _lock = new object();
public static T Instance
{
get
{
lock (_lock)
{
if (_insatnce == null)
{
var instances = FindObjectsOfType<T>();
if (instances.Length > 1)
{
throw new Exception(string.Format("场景中存在多个类型为:{0}的脚本", typeof(T).ToString()));
}
else if (instances.Length == 0)
{
var go = new GameObject(typeof(T).ToString() + "(MonoSingleton)");
go.hideFlags = HideFlags.HideInHierarchy;
_insatnce = go.AddComponent<T>();
_insatnce.Init();
DontDestroyOnLoad(go);
}
else
{
_insatnce = instances[0];
}
}
return _insatnce;
}
}
}
/// <summary>
/// 初始化函数
/// </summary>
protected abstract void Init();
protected virtual void OnApplicationQuit()
{
_insatnce = null;
}
protected virtual void OnDestory()
{
_insatnce = null;
}
}wiki上的继承Monobehavior的单例:http://wiki.unity3d.com/index...
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论