Aspect
概念:
-
ASPECT是一种用于描述Entity的特性或特征的概念。ASPECT通常用于在系统中筛选出具有特定组件集合的实体。 你可以把5~6个组件得引用保存到一个数据对象里面(Aspect),你通过Aspect就可以拿到这些组件得引用,从而访问这些组件数据;
-
Unity 会为关联的Components组,提供预定义好的aspects。你也可以通过IAspect接口定义自己的Aspect
-
Aspect 可以包含的字段类型:
- Entity字段:存放EntityID
- ComponentData的引用:RefRW与RefRO
- EnabledRefRW与EnabledRefRO fields,可以包含Enbale Component的这个引用,可读写,或只读;
- DynamicBuffer:这个是可以包含; IBufferElementData
- lSharedComponent:类型的字段;读取共享的ComponentData;
- Other aspect types: 也可以在你的Aspect里面引入其它的Aspect;
创建一个Aspect
-
定义一个Aspect类型: readonly partial stuct 类名 : IAspet{}
-
当你定义了好一个Aspect类以后,定义与entity对应组件的引用,再用Entity创建Aspect实例,这样当Aspect初始化好了,字段的里面就是Entity中的component数据的引用;
-
实例:
using Unity.Entities;
readonly partial struct MyAspect : IAspect
{RefRW<transform> a;
}aspect = new Aspect(Enity);
Aspectt.a //这个就是Entity的Transfrom
-
如果某个字段可以不用制定值: [Optional]来修饰这个字段; 那么这个字段就不是必须的;
-
Apsect就是开发某个代码逻辑的时候,需要entity里面的一些组件时,就定以一个Aspect,然后里面包含了这些引用。
-
在System中可以通过SystemAPI.GetAspect 来获得一个Entity的Aspect实例:
MyAspect asp = SystemAPI.GetAspect<MyAspect>(myEntity);
- 在System外,可使用EntityManager.GetAspect 获取
- 迭代World Entity中某个特定的Aspect,使用SystemAPI.Query来查询
实例代码:
struct CannonBall : IComponentData{public float3 Speed;}// Aspects must be declared as a readonly partial structreadonly partial struct CannonBallAspect : IAspect{// An Entity field in an Aspect gives access to the Entity itself.// This is required for registering commands in an EntityCommandBuffer for example.public readonly Entity Self;// Aspects can contain other aspects.// A RefRW field provides read write access to a component. If the aspect is taken as an "in"// parameter, the field behaves as if it was a RefRO and throws exceptions on write attempts.readonly RefRW<LocalTransform> Transform;readonly RefRW<CannonBall> CannonBall;// Properties like this aren't mandatory. The Transform field can be public instead.// But they improve readability by avoiding chains of "aspect.aspect.aspect.component.value.value".public float3 Position{get => Transform.ValueRO.Position;set => Transform.ValueRW.Position = value;}public float3 Speed{get => CannonBall.ValueRO.Speed;set => CannonBall.ValueRW.Speed = value;}}public partial struct MySystem : ISystem{public void OnUpdate(ref SystemState state){foreach (var cannonball in SystemAPI.Query<CannonBallAspect>()){// use cannonball aspect here}}}