Fork me on GitHub

HelloCube:IJobForEach

此示例演示了基于作业的ECS系统,该系统可旋转一对立方体。

它显示了什么?

此示例基于ForEach示例构建,并说明如何在多线程作业中执行相同的工作,而不是在主线程上执行相同的工作。

与前面的示例一样,RotationSpeedSystem_IJobForEach 使用存储在RotationSpeed_IJobForEach组件中的数据更新对象的旋转。

JobComponentSystems和IJobForEach

使用IJobForEach的系统是您可以用来处理组件数据的最简单,最有效的方法。对于您设计的任何系统,我们建议从此方法开始

在此示例中,RotationSpeedSystem_IJobForEach实现为JobComponentSystem。该类创建一个IJobForEach结构来定义需要完成的工作。此作业计划在System的OnUpdate()函数中。

 1 using Unity.Burst;
 2 using Unity.Collections;
 3 using Unity.Entities;
 4 using Unity.Jobs;
 5 using Unity.Mathematics;
 6 using Unity.Transforms;
 7 using UnityEngine;
 8 
 9 // This system updates all entities in the scene with both a RotationSpeed_IJobForEach and Rotation component.
10 public class RotationSpeedSystem_IJobForEach : JobComponentSystem
11 {
12      // Use the [BurstCompile] attribute to compile a job with Burst. You may see significant speed ups, so try it!
13      [BurstCompile]
14      struct RotationSpeedJob : IJobForEach<Rotation, RotationSpeed_IJobForEach>
15      {
16          public float DeltaTime;
17 
18         // The [ReadOnly] attribute tells the job scheduler that this job will not write to rotSpeedIJobForEach
19          public void Execute(ref Rotation rotation, [ReadOnly] ref RotationSpeed_IJobForEach rotSpeedIJobForEach)
20          {
21              // Rotate something about its up vector at the speed given by RotationSpeed_IJobForEach.
22              rotation.Value = math.mul(math.normalize(rotation.Value), quaternion.AxisAngle(math.up(), rotSpeedIJobForEach.RadiansPerSecond * DeltaTime));
23          }
24      }
25 
26     // OnUpdate runs on the main thread.
27      protected override JobHandle OnUpdate(JobHandle inputDependencies)
28      {
29          var job = new RotationSpeedJob
30          {
31              DeltaTime = Time.deltaTime
32          };
33 
34         return job.Schedule(this, inputDependencies);
35      }
36 }
View Code

 

posted @ 2019-08-09 15:25  gamedev'  阅读(312)  评论(0编辑  收藏  举报