【Unity3D】ECS入门学习(十一)ComponentSystem、JobComponentSystem

发布于:2025-02-11 ⋅ 阅读:(98) ⋅ 点赞:(0)

 ComponentSystem:仅支持主线程执行,不支持多线程,并且无法使用SystemBase介绍的扩展方法。

using Unity.Entities;
using Unity.Transforms;
using Unity.Mathematics;

/// <summary>
/// 仅主线程执行,不支持多线程
/// </summary>
public class MyComponentSystem : ComponentSystem
{
    protected override void OnUpdate()
    {
        Entities.ForEach((ref Translation trans) =>
        {
            trans.Value = new float3(0, 1, 1);
        });//无法使用SystemBase的其他扩展功能
    }
}

JobComponentSystem:仅支持多线程,不支持主线程,可以使用扩展方法,并且重写的方法与其他都不同,它需要一个JobHandle返回值 

using Unity.Entities;
using Unity.Jobs;
using Unity.Transforms;
/// <summary>
/// 支持多线程 但不支持主线程执行
/// </summary>
public class MyJobComponentSystem : JobComponentSystem
{
    protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
        return Entities.ForEach((ref Translation trans) =>
        {
            trans.Value = new Unity.Mathematics.float3(0, 0, 1);
        }).WithName("MyName").Schedule(inputDeps);//可以使用SystemBase扩展方法
    }
}

具体文档:Using Entities.ForEach | Entities | 0.50.1-preview.2

如下图是三个执行筛选的方法限制,简单理解就是:
Run:非Burst编译下 可访问所有成员,可修改实体。【主线程执行】
Schedule:仅能获取局部成员,可修改实体。【新开一个后台线程执行】
ScheduleParallel:仅能获取局部成员,可以读取实体,但不能修改实体,并且可读数据只允许存储到WithReadOnly(xxx)方法标记的只读变量内。【多线程并行执行】

Supported Feature Run Schedule ScheduleParallel
Capture local value type x x x
Capture local reference type x (only WithoutBurst and not in ISystem)
Writing to captured variables x
Use field on the system class x (only WithoutBurst)
Methods on reference types x (only WithoutBurst and not in ISystem)
Shared Components x (only WithoutBurst and not in ISystem)
Managed Components x (only WithoutBurst and not in ISystem)
Structural changes x (only WithStructuralChanges and not in ISystem)
SystemBase.GetComponent x x x
SystemBase.SetComponent x x
GetComponentDataFromEntity x x x (only as ReadOnly)
HasComponent x x x
WithDisposeOnCompletion x x x
WithScheduleGranularity x

网站公告

今日签到

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