Unity万能单例框架

1.0 需要挂载游戏对象的单例类

 public abstract class SingletonBaseMono : MonoBehaviour where T : SingletonBaseMono
{
    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();
                }
                else
                {
                    if (go.GetComponent() == null)
                    {
                        go.AddComponent();
                    }
                    _Instance = go.GetComponent();
                }
                //在切换场景的时候不要释放这个对象
                DontDestroyOnLoad(go);
            }
            return _Instance;
        }
    }
}               

2.0 数据类单例

public class SingletonBase 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()
    {

    }
}

你可能感兴趣的:(unity3d,c#)