今天我們來研究一下第三個Sample
HelloCube_03_IJobChunk
RotationSpeed.cs 和 RotationSpeedProxy.cs 沒有變化,上篇也介紹了作用,現在就不贅述了
我們直接來看RotationSpeedSystem.cs
這個類繼承於JobComponentSystem抽象類
我們來讀讀代碼:
OnCreate方法
這裏複寫了OnCreate方法,在此方法中保存了指定實體的查詢條件
RotationSpeedJob結構體
結構體繼承於IJobChunk
struct RotationSpeedJob : IJobChunk
在這個結構體中保存了Execute方法執行所需的數據
1. 每幀執行時間,用於平滑旋轉
public float DeltaTime;
2.儲存Rotation 原型塊的組件類型爲讀寫
public ArchetypeChunkComponentType<Rotation> RotationType;
3.儲存RotationSpeed 原型塊的組件類型爲只讀
[ReadOnly] public ArchetypeChunkComponentType<RotationSpeed> RotationSpeedType;
最後看一下執行方法 Execute
public void Execute(ArchetypeChunk chunk, int chunkIndex, int firstEntityIndex)
參數1 ArchetypeChunk 原型數據塊, 裏面儲存了實體的數據
參數2 和參數3在這個例子裏面沒有用到就先不研究
Execute中主要看這個方法
public NativeArray<T> GetNativeArray<T>(ArchetypeChunkComponentType<T> chunkComponentType) where T : struct, IComponentData;
從原型數據塊中 查找出RotationType類型的所有數據
NativeArray<Rotation> chunkRotations = chunk.GetNativeArray(RotationType);
同上,從原型數據塊中 查找出RotationSpeedType類型的所有數據
NativeArray<RotationSpeed> chunkRotationSpeeds = chunk.GetNativeArray(RotationSpeedType);
後面就是循環遍歷數據塊
數據塊的下標和查詢出來數據的下標是一致的,所以可以根據數據塊的下標來遍歷我們的Rotation和RotationSpeed
然後修改Rotation的旋轉數值
現在IJobChunk結構體我們就看完了
最後來看OnUpdate
protected override JobHandle OnUpdate(JobHandle inputDependencies)
這個OnUpdate方法是運行在主線程上的
在前兩行代碼中顯示的聲明瞭
rotationType爲可讀寫的類型
RotationSpeed爲只讀類型
並且保存了這兩個屬性的組件類型,用於在原型數據塊中查找Rotation和RotationSpeed
後面就跟之前一樣,創建RotationSpeedJob 把屬性賦值
最後return 執行job 帶入 m_Group(指定實體的查詢條件)
到這裏第三個Sample就講完了
下面附上方法執行順序
↓OnCreate
↓Convert
↓OnUpdate(一幀執行一次,而不是每個實體(Entiry)執行一次)
Execute ↑
每幀執行一次OnUpdate和Execute 不論有多少個實體(Entiry)