UnityDots学习(二)

发布于:2025-02-10 ⋅ 阅读:(60) ⋅ 点赞:(0)

在一里已经概述了什么是Dots,已经如果使用它,我们要做的思维转变。

简单总结下:

Dots使用了计算器多核,已经3级缓存的优势,在此基础上使用Brust编译器对各个平台实现了代码优化。从而达到了加速提升的效果。

我们要从面相对象的思维转变为面相数据的思维。

此篇开始记录学习Unity官网学习思路。

Job

我的理解是他是可以单独在某个核上跑的一段逻辑程序。

在Unity上大概张这样

 public struct FindNearestJob : IJob
    {
        [ReadOnly] public NativeArray<float3> TargetPositions;
        [ReadOnly] public NativeArray<float3> SeekerPositions;

        public NativeArray<float3> NearestTargetPositions;

        // 'Execute' is the only method of the IJob interface.
        // When a worker thread executes the job, it calls this method.
        public void Execute()
        {
            // Compute the square distance from each seeker to every target.
            for (int i = 0; i < SeekerPositions.Length; i++)
            {
                float3 seekerPos = SeekerPositions[i];
                float nearestDistSq = float.MaxValue;
                for (int j = 0; j < TargetPositions.Length; j++)
                {
                    float3 targetPos = TargetPositions[j];
                    float distSq = math.distancesq(seekerPos, targetPos);
                    if (distSq < nearestDistSq)
                    {
                        nearestDistSq = distSq;
                        NearestTargetPositions[i] = targetPos;
                    }
                }
            }
        }
    }

当某些逻辑依赖别的逻辑完成后执行,需要实现的代码逻辑如下

更复杂点的:

Unity也可以按指定批次完成Job如下:

Entities and Components

Component是一个数据单元

定义大概如下:

 public struct MoveComponent: IComponentData
    {
        public float3 Direct;
        public float Speed;
    }

需要注意的是,尽可能使用非托管对象。否则会出现无法被Brust编译。并且不能使用3级缓存存储数据。导致无法将Dots功能效率最大化。

Entity是Component的一个集合。受到World管理,每个World下每个Entity的Id是唯一的。由EntityManager进行管理

World会对持有不同类型数量的Entity进行分块管理如下所示

同时有ABC组件在1号块,AB在2号块,AC在3号块。

如果这时候我从ABC组件取到1个Entity实体删除其C组件。那么他会移动到2号块。这么处理的好处是数据Entity可以分批次直接处理。免得中间处理大量复杂的过程。

对于Entity的查询,提供了二种方式,一个为单个的,一个为符合条件的

Systems

理解为处理World下每个Entity的逻辑。简单理解为xxManager

张的如下所示

定义执行顺序

可以查看执行顺序

Baking

首先Baking是把Unity的如Gameobject这种托管对象转换为非托管对象,进而可以使用Dots进行编译加速的一个过程。

Unity提供了二种烘焙方式

SubScene实现方式:

多出来的子场景可以创建物体。这样运行时,unity自动把subscene的东西进行Baking

自己控制实现Baking:

把脚本挂到对应GameObject上运行时就Baking该物体了

下一篇学习记录实战内容


网站公告

今日签到

点亮在社区的每一天
去签到