【Unity】【ARPG开发日志】【二】【04】利用Generics泛型实现组件&脚本的绑定

有时候在一个脚本中需要绑定多个脚本,使用下面这种方式会造成了大量的代码冗余。可以使用泛型方法进行简化。

冗余的绑定方法

void Awake()
      	bm = sensor.GetComponent<BattleManager>();
        if (!bm)
        {
            bm = sensor.AddComponent<BattleManager>();
        }
        bm.am = this;

        wm = model.GetComponent<WeaponManager>();
        if (!wm)
        {
            wm = model.AddComponent<WeaponManager>();
        }
        wm.am = this;
        ......
}

使用Generics 泛型方法简化

    private T Bind<T>(GameObject go) where T : IActorManagerInterface
    {
        T tempInstance;
        tempInstance = go.GetComponent<T>();
        if (!tempInstance)
        {
            tempInstance = go.AddComponent<T>();
        }
        tempInstance.am = this;
        return tempInstance;
    }

可以看到优化代码后 简单多了。

void Awake()
       bm = Bind<BattleManager>(sensor);
       wm = Bind<WeaponManager>(model);
       ......
}

关于泛型约束

  • where T : class

约束T参数必须为 引用类型

  • where T :

类型参数必须是指定的接口或实现指定的接口。可以指定多个接口约束。约束接口也可以是泛型的。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值