using System;
using UnityEngine;
///
/// 单键类
///
///
public abstract class MonoSingleton : MonoBehaviour where T : MonoSingleton
{
///
/// 单键
///
private static T m_Instance;
///
/// 单键
///
public static T Instance
{
get
{
if (object.ReferenceEquals(MonoSingleton.m_Instance, null))
{
GameObject obj = new GameObject(typeof(T).ToString());
obj.transform.parent = Container.transform;
MonoSingleton.m_Instance = obj.AddComponent();
}
return MonoSingleton.m_Instance;
}
}
static GameObject _mC;
static GameObject Container
{
get
{
if (null == _mC)
{
_mC = GameObject.Find("MonoSingleton");
}
if (null == _mC)
{
_mC = new GameObject("MonoSingleton");
DontDestroyOnLoad(_mC);
}
return _mC;
}
}
///
/// 单键是否有效
///
public static bool IsInstanceValid
{
get
{
return !object.ReferenceEquals(MonoSingleton.m_Instance, null);
}
}
///
/// 初始化
///
private void Awake()
{
if (object.ReferenceEquals(MonoSingleton.m_Instance, null))
{
MonoSingleton.m_Instance = (this as T);
MonoSingleton.m_Instance.OnAwake();
}
}
///
/// 初始化
///
protected virtual void OnAwake()
{
}
///
/// 销毁
///
protected virtual void DoOnDestroy()
{
}
///
/// 销毁
///
private void OnDestroy()
{
this.DoOnDestroy();
if (object.ReferenceEquals(MonoSingleton.m_Instance, this))
{
MonoSingleton.m_Instance = (T)((object)null);
}
}
}