任务17:ComponentFactory静态类的理解和使用
ET框架提供了静态类 ComponentFactory,帮我们快速创建实体的实例。前面课时已经多次用到了,怎么添加组件,和传参给这个组件的扩展方法,理解他并灵活运用,经常用到。
在ET4-5版本中,实体是一种组件的派生类,创建实体其实也就是创建组件,用的是ComponentFactory来快速创建实体实例。从6.0开始实体继承Object,不再是组件的派生类了,所以提供了静态类EntityFactory。
ComponentFactory提供的CreateWithId,Create方法是常用的,前面的课程我们已经用到了。
public static T CreateWithId<T>(long id, bool fromPool = true) where T : ComponentWithId public static T CreateWithId<T, A>(long id, A a, bool fromPool = true) where T : ComponentWithId public static T Create<T, A>(A a, bool fromPool = true) where T : Component
RegisterHandler中的应用
\Server\Hotfix\Landlords\Handler\Realm\A0001_RegisterHandler.cs
用来创建数据库实体的实例,可以用此实例保存数据到MongoDB,也可以用来接受从数据库查询到的结果。
ComponentFactory.CreateWithId<T>
如果我们的实体类不需要Awake扩展方法,比如AccountInfo这个数据实体,就用这种格式定义的CreateWithId方法。
即便是新手也可以体会和使用泛型,你可以看 ComponentFactory.CreateWithId<T>方法的定义,使用起来也不难理解了吧。
如果你要创建AccountInfo的实例,T就是AccountInfo,<型参>尖括号内我们把类型作为参数传进去,CreateWithId方法就会用这个类型构建实例。
AccountInfo newAccount = ComponentFactory.CreateWithId<AccountInfo>(154244112541)
CreateWithId方法再用传入的参数id(long id)作为创建的实体的ID,项目中是用RealmHelper.GenerateId()方法生成的ID,这种ID确保了唯一性,里面的代码也很好理解。
还把这个实体加入到Awake事件系统:Game.EventSystem.Awake(component);
AccountInfo类并没有定义自己的Awake扩展方法,没有Awake方法可触发。
ComponentFactory.CreateWithId<T, A>
如果我们的实体类需要定义Awake扩展方法,比如UserInfo这个数据实体,就用这种CreateWithId方法。
UserInfo newUser = ComponentFactory.CreateWithId<UserInfo, string>(newAccount.Id, request.Account); await dbProxy.Save(newUser);
CreateWithId方法再用传入的参数account.Id作为创建的实体的ID,第二个参数账号名作为UserInfo的扩展方法的传入参数。所以<UserInfo,string>第二个型参,就是UserInfo扩展方法的传入参数类型。
而UserInfo定义有Awake扩展方法,所以创建实例后就会触发。
LoginGateHanler中的应用
\Server\Hotfix\Landlords\Handler\Gate\A0003_LoginGateHanler.cs
我们要在登录验证后,会创建User这个网关实体的实例,我们需要把gateUserID传入到User中,就可以用:
ComponentFactory.Create<T, A>
//gateUserID传参创建User User user = ComponentFactory.Create<User, long>(gateUserID);
这种实体类,我们并不需要根据某种ID来创建,所以用Create方法,区别于上面讲的CreateWithId方法。
同样的<User,long>第二个型参,就是User扩展方法的传入参数类型。
思考,比如说定义一个实体 Boss 可不可以这样使用?
Boss boss = ComponentFactory.Create<Boss, string>(bossName);
那Boss的扩展方法的参数类型是什么呢?
通过本节的学习,大家要多尝试,掌握ComponentFactory静态类的使用,灵活使用和定义实体对象的扩展方法。