Unity单例框架

普通单例

//普通的单例类我们一般这样来创建

public class SingleTon : MonoBehaviour
{
    private static SingleTon Instance = null;

    //防止外界New
    private SingleTon()
    {

    }

    private void Awake()
    {
        if(Instance == null) Instance = this;
        else Destroy(gameObject);
    }

}

单例框架 第一种 需要继承并挂载在游戏物体上 那么我们必须要先继承MonoBehaviour

//这里的where T 是泛型约束
public class SingleTon<T> : MonoBehaviour where T : SingleTon<T>
{
    public static T Instance
    {
        get;
        private set;
    }

    private void Awake()
    {
        if (Instance == null)
        {
            Instance = (T)this;
            DontDestroyOnLoad(gameObject);
        }
        else
        {
            Destroy(gameObject);
        }
    }

}

单例框架 第二种 不需要继承并挂载在游戏物体

public class SingleScript<T> where T : new()
{
    private static T instance = default(T);

    public static T GetInstance()
    {
        if (instance == null)
        {
            instance = new T();
        }
        return instance;
    }
}

posted @ 2021-07-13 17:16  yassine  阅读(141)  评论(0编辑  收藏  举报