【Dots之003】SystemAPI.Query相关基础笔记
1、SystemAPI.Query
注:SystemAPI.Query只能作为foreach中in的的子句
SystemAPI.Query<RefRO<LocalTransform>>().WithAll<Obstacle>()
解析:对于每个具有LocalTransform和Obstacle的Entity;都会将LocalTransform的只读引用返回给查询结果
SystemAPI.Query<RefRW<LocalTransform>, RefRW<Velocity>>().WithAll<Ball>()
解析:查询具有LocalTransform,Velocity,Ball组件的Entity,将LocalTransform和Velocity的可读写引用返回,用于可读可修改
2、LocalTransform
不设置默认的Scale和Rotation属性
state.EntityManager.SetComponentData(player, new LocalTransform());
可以看到默认都是设置为0;
设置的默认属性以后:
state.EntityManager.SetComponentData(player, new LocalTransform{Position = new float3{x = obstacleTransform.ValueRO.Position.x + config.PlayerOffset,y = 1,z = obstacleTransform.ValueRO.Position.z + config.PlayerOffset},Scale = 1, // If we didn't set Scale and Rotation, they would default to zero (which is bad!)Rotation = quaternion.identity});
给Entity添加LocalTransform需要设置默认的Scale和Rotation;上面的代码中没有设置,得到的结果会如下:
现在就是正常的状态了;
3、Unity.Mathematics.Random
首先根据情况决定是否需要设置一个随机种子;然后在进行调用;
var rand = new Random(123);
//随机一个值
float random_one = rand.NextFloat(0, 100);
//随机一个2为向量
float2 random_v2 = rand.NextFloat2(new float2(0, 0), new float2(100, 100));
//随机一个方向
random_v2 = rand.NextFloat2Direction();
4、EntityQuery
获取或者创建与查询描述匹配的EntiyQuery
如果System中没有匹配的EntityQuery,那么就Create一个;如果有就直接Get
//描述同时具有Obstacle和LocalTransform组件的EntityQuery
var obstacleQuery = SystemAPI.QueryBuilder().WithAll<LocalTransform, Obstacle>().Build();
5、IEnableableComponent
组件继承IEnableableComponent,可以起到开启和关闭组件的作用;而不需要把该组件从Entity上面移除;
1、启用组件:SetComponentEnabled(entity,true);
2、关闭组件:SetComponentEnabled(entity,false);
public override void Bake(PlayerAuthoring authoring){var entity = GetEntity(TransformUsageFlags.Dynamic);AddComponent<Player>(entity); AddComponent<Carry>(entity);//设置是否启用ComponentDataSetComponentEnabled<Carry>(entity, false);}public struct Carry : IComponentData, IEnableableComponent{}
3、如果通过IJobEntity的方式来处理组件的启用与否,可以参考下面的这种方式:
[WithAll(typeof(Turret))][WithOptions(EntityQueryOptions.IgnoreComponentEnabledState)][BurstCompile]public partial struct SafeZoneJob : IJobEntity{public float SquaredRadius;// Because we want the global position of a child entity, we read LocalToWorld instead of LocalTransform.void Execute(in LocalToWorld transformMatrix, EnabledRefRW<Carry> shootingState){//组件的启用状态shootingState.ValueRW = math.lengthsq(transformMatrix.Position) > SquaredRadius;}}
EnabledRefRW后面的类型必须要继承IEnableableComponent;