Dots之路-核心包_JobSystem_01_WaveCube示例

前言

本文为 Metaverse大衍神君 Dots 之路的记录。
仓库地址 RoadToDotsTutorials

基于 GameObject Component 方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
void Start()
{
cubesList = new List<Transform>();
for (var z = -zHalfCount; z <= zHalfCount; z++)
{
for (var x = -xHalfCount; x <= xHalfCount; x++)
{
var cube = Instantiate(cubeAchetype);
cube.transform.position = new Vector3(x * 1.1f, 0, z * 1.1f);
cubesList.Add(cube.transform);
}
}
}

// Update is called once per frame
void Update()
{
using (profilerMarker.Auto(cubesList.Count))
{
for (var i = 0; i < cubesList.Count; i++)
{
var distance = Vector3.Distance(cubesList[i].position, Vector3.zero);
cubesList[i].localPosition += Vector3.up * Mathf.Sin(Time.time * 3f + distance * 0.2f);
}
}
}

基于 Job 方式

1
2
3
4
5
6
7
8
9
10
11
12
// 位置更新逻辑
[BurstCompile]
struct WaveCubesJob : IJobParallelForTransform
{
[ReadOnly] public float elapsedTime;

public void Execute(int index, TransformAccess transform)
{
var distance = Vector3.Distance(transform.position, Vector3.zero);
transform.localPosition += Vector3.up * math.sin(elapsedTime * 3f + distance * 0.2f);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
public class WaveCubesWithJobs : MonoBehaviour
{
static readonly ProfilerMarker<int> profilerMarker = new ProfilerMarker<int>("WaveCubesWithJobs UpdateTransform", "Objects Count");
public GameObject cubeAchetype = null;
[Range(10, 100)] public int xHalfCount = 40;
[Range(10, 100)] public int zHalfCount = 40;

private TransformAccessArray transformAccessArray;

void Start()
{
transformAccessArray = new TransformAccessArray(4 * xHalfCount * zHalfCount);
for (var z = -zHalfCount; z < zHalfCount; z++)
{
for (var x = -xHalfCount; x < xHalfCount; x++)
{
var cube = Instantiate(cubeAchetype);
cube.transform.position = new Vector3(x * 1.1f, 0, z * 1.1f);
transformAccessArray.Add(cube.transform);
}
}
}

void Update()
{
Debug.Log($"TransformAccessArray length: {transformAccessArray.length}");
using (profilerMarker.Auto(transformAccessArray.length))
{
var waveCubesJob = new WaveCubesJob
{
elapsedTime = Time.time,
};
JobHandle waveCubesJobhandle = waveCubesJob.Schedule(transformAccessArray);

waveCubesJobhandle.Complete(); // 同步到主线程中
}
}

private void OnDestroy()
{
transformAccessArray.Dispose();
}
}
  • TransformAccessArray (struct): Job 只能使用 Blittable 类型数据和非托管内存堆上的数据,Transform 并不符合要求
  • BurstCompile: 使用此标签的部分代码将使用 Brust 编译,可以用于一下内容
    1. Jobs: burst 将会编译 jobs 内的所有内容
    2. Classes:
    3. Structs:
    4. Static methods:
    5. Assemblies:

Dots之路-核心包_JobSystem_01_WaveCube示例
https://lshgame.com/2025/09/27/Dots_Road_Core_Package_JobSystem_01_WaveCube_Example/
作者
SuHang
发布于
2025年9月27日
许可协议