强悍の绝巴哈

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

单例

public class Singleton<T> where T : new()
{
    private static T instance;

    public static T Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new T();
            }

            return instance;
        }
    }
}

Unity中的mono单例

public class Singleton<T> : MonoBehaviour where T : Singleton<T>
{
    private static T instance;

    public static T Instance { get => instance; }

    protected virtual void Awake()
    {
        
        if(instance != null)
            Destroy(this);
        instance = (T)this;
    }
}
posted on 2022-12-26 23:50  强悍の绝巴哈  阅读(48)  评论(0编辑  收藏  举报