有时候在一个脚本中需要绑定多个脚本,使用下面这种方式会造成了大量的代码冗余。可以使用泛型方法进行简化。
冗余的绑定方法
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 :
类型参数必须是指定的接口或实现指定的接口。可以指定多个接口约束。约束接口也可以是泛型的。