Unity DOTS系列之System中如何使用SystemAPI.Query迭代数据

发布时间 2023-11-10 10:32:33作者: rain4414

最近DOTS发布了正式的版本, 我们来分享一下System中如何基于SystemAPI.Query来迭代World中的数据,方便大家上手学习掌握Unity DOTS开发。

SystemAPI.Query的使用

System有两种,一种是Unmanaged ISystem,一种是managed SystemBase,这两种System都可以通过SystemAPI.Query来迭代与遍历,可以获取World里面的组件与EntitySystemAPI.Query是运行在main thread的主线程上,SystemAPI.QueryC# 传统的foreach语句结合起来,让我们遍历数据非常的方便。当我们要遍历一个World里面的entity数据的时候,我们需要根据数据类型来筛选出对应的组件与Entity。函数SystemAPI.Query<T1,T2…>(),其中t1, t2就是我们需要的component data的类型,查询的时候,会遍历World 里面有这些组件的Entity,获取组件的引用。Query中的类型T1,T2,可以是以下7中类型:

IAspect

IComponentData

ISharedComponentData

DynamicBuffer<T>

RefRO<T>

RefRW<T>

EnabledRefRO<T> where T : IEnableableComponent, IComponentData

EnabledRefRW<T> where T : IEnableableComponent, IComponentData

以下是给的一个代码示例,从World里面筛选出来有LocalTransformRotationSpeed组件的Entity,并把它们的数据通过foreach来处理。示例代码如下:

    public partial struct MyRotationSpeedSystem : ISystem

    {

 

        [BurstCompile]

        public void OnUpdate(ref SystemState state)

        {

            float deltaTime = SystemAPI.Time.DeltaTime;

 

            foreach (var (transform, speed) in SystemAPI.Query<RefRW<LocalTransform>, RefRO<RotationSpeed>>())

                transform.ValueRW = transform.ValueRO.RotateY(speed.ValueRO.RadiansPerSecond * deltaTime);

        }

    }

RefRW<T>.ValueRW获取组件的可读写权限的组件引用, RefRW<T>.ValueRO只读属性的组件应用, RefRO<T>.ValueRO组件的只读引用。如果你只要一个只读之间,我们就可以单纯的用组件的名字来Query就可以了。

        public void OnUpdate(ref SystemState state)

        {

            #region query-data-alt

            float deltaTime = SystemAPI.Time.DeltaTime;

 

            foreach (var (transform, speed) in SystemAPI.Query<RefRW<LocalTransform>, RotationSpeed>())

                transform.ValueRW = transform.ValueRO.RotateY(speed.RadiansPerSecond * deltaTime);

            #endregion

        }

其中RotaionSpeed为只读的组件实例的引用。如果我们在system里面迭代数据的时候,需要组件对应的Entity,我们使用API函数WithEntityAcess,示例代码如下:

 public void OnUpdate(ref SystemState state)

        {

            float deltaTime = SystemAPI.Time.DeltaTime;

 

            #region entity-access

            foreach (var (transform, speed, entity) in SystemAPI.Query<RefRW<LocalToWorld>, RefRO<RotationSpeed>>().WithEntityAccess())

            {

                // Do stuff;

            }

            #endregion

        }

 

 

SystemAPI.Query的内部实现

当我们在System代码里面调用foreach+SystemAPI.Query的时候,我们的自动代码生成器会根据Query调用的时候传递的参数的类型来生成EntityQuery字段到当前的System类里面(正因如此,我们在定义一个System类型的时候都要加partial)。同时替换掉SystemAPI.Query代码。这样运行的时候使用EntityQuery字段来帮我们找到对应的组件来进行迭代处理。SystemAPI.Query也有它的一些局限性,使用SystemAPI.Query API的时候我们无法对Dynamic Buffer组件来做只读的访问权限,只能获得可读写的访问权限。我们不能够保存foreach的结果,因为foreach是自动代码生成的时候,根据foreach在编译的时候自动生成的EntityQuery,没有办法去缓存EntityQuery的结果。

 

 

今天的 SystemAPI.Query如何使用,就到这里了,更多的DOTS系列,关注我们,持续更新!