1.0 需要挂载游戏对象的单例类
public abstract class SingletonBaseMono<T> : MonoBehaviour where T : SingletonBaseMono<T>
{
protected static T _Instance = null;
public static T Instance
{
get
{
if (null == _Instance)
{
//寻找是否存在当前单例类对象
GameObject go = GameObject.Find(typeof(T).Name);
//不存在的话
if (go == null)
{
//new一个并添加一个单例脚本
go = new GameObject();
_Instance = go.AddComponent<T>();
}
else
{
if (go.GetComponent<T>() == null)
{
go.AddComponent<T>();
}
_Instance = go.GetComponent<T>();
}
//在切换场景的时候不要释放这个对象
DontDestroyOnLoad(go);
}
return _Instance;
}
}
}
2.0 数据类单例
public class SingletonBase<T> where T : class ,new()
{
private static T _instance=null;
public static T Instance
{
get
{
if (_instance == null)
{
_instance = new T();
}
return _instance;
}
}
//构造的同时调用初始化函数
protected SingletonBase()
{
if (null != _instance)
Init();
}
public virtual void Init()
{
}
}