【Dots之003】SystemAPI.Query相关基础笔记

1、SystemAPI.Query

SystemAPI.Query只能作为foreach中in的的子句

SystemAPI.Query<RefRO<LocalTransform>>().WithAll<Obstacle>()

解析:对于每个具有LocalTransformObstacleEntity;都会将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需要设置默认的ScaleRotation;上面的代码中没有设置,得到的结果会如下:
在这里插入图片描述
现在就是正常的状态了;

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);
       //设置是否启用ComponentData
       SetComponentEnabled<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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值