unity 实用框架

单例模式基类

类不继承mono的单例基类

/// <summary>
/// 单例基类
/// </summary>
//泛型解决,给他一个约束要么是这个类本身要么是它的子类
public class SingleBase<T>where T : SingleBase<T>
{
    protected SingleBase() { }

    //线程锁。当多线程访问时,同一时刻仅允许一个线程访问。
    private static object locker=new object();

    //volatile关键字修饰字段是当多个线程都对他进行修改时,确保这个字段在任何时刻呈现都是最新的值
    private volatile  static T _instance;
    public static T Instance
    {
        get
        {
            //双重保证对象的唯一性
            if (_instance == null)
            {
                lock (locker)
                {
                    if (_instance == null)
                    {
                        //使用反射调用无参构造方法创建对象,就是new一个对象的意思
                        _instance = Activator.CreateInstance(typeof(T), true) as T;
                    }
                }
            }
            return _instance;
        }
    }
}

继承单例基类就不用再写了

public class PlayerModel:SingleBase<PlayerModel>
{
    private PlayerModel() { }
    
    public int money=1000;

    public int diamond = 888;

    public void Show()
    {
        Debug.Log(money);
        Debug.Log(diamond);
    }
}
PlayerModel.Instance.Show();

类继承mono的单例基类

/// <summary>
/// 继承monobehaviour的单例基类,前面是继承,where后面是泛型约束,要么是本身,要么是继承monobehaviour
/// </summary>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值