美文网首页
Unity ECS JobSystem BurstCompile

Unity ECS JobSystem BurstCompile

作者: 无聊盒子 | 来源:发表于2019-04-01 13:41 被阅读0次

    ECS

    E:Entities contain Components
    C:Component contain data
    S:System contain behaviour

    ECS是Untiy版本更新到2018之后提出的一种新的结构方式。

    Entity Component System Benefits
    1.Performance by Default
    2.Easier to write highly optimized code
    3.Easier to write reusable code
    4.Leverage modern hardware architecture
    5.Archetypes are tightly packed in memory
    6.Burst compiler love < 3

    image

    小插曲:如果电脑注册表的Time Zones.reg被第三方软件优化掉了,或者被破坏掉了。Unity2018以上的版本启动的时候读取不到时区,就会编译报错。就会很尴尬的在下面一步操作将Scripting Runtime Version切换到.Net 4.x Equivalent的时候工程无限卡死。只要恢复Time Zones.reg就OK了。

    用uinty2018.1(最好使用正式版,我用2018.3的beta版在配置Json文件是报错)以上版本创建工程,然后修改设置。

    Edit->Project Settings->Player->Scripting Runtime Versiong 切换到 .Net 4.x Equivalent 。然后工程重启即可。
    然后修改工程根目录下Packages/manifest.json文件

    ,
      "registry": "https://packages.unity.com",
      "testables": [
        "com.unity.collections",
        "com.unity.entities",
        "com.unity.jobs",
        "com.unity.test-framework.performance"
      ]
    

    工程就会导入ECS、JobSystem、BurstCompiler,然后菜单栏就有了Jobs选项。


    image.png

    创建一个Cube,再添加一个脚本Rotator.cs,之前的写法是

    public class Rotator : MonoBehaviour
    {
        public float speed;
        public void Update()
        {
            transform.Rotate(0f, speed * Time.deltaTime, 0f);
        }
    }
    

    逻辑与数据都放在mono控件里面的。而ECS则是将数据与逻辑拆分开来,用一个相对独立的系统来进行表现。

    看上去代码多了些,但是逻辑与数据分离了,显得更清晰了。对比一下

    class RotatorSystem : ComponentSystem
    {
        protected override void OnUpdate()
        {
            Entities.ForEach((Rotator rotator) => {
                rotator.transform.Rotate(0f, rotator.speed * Time.deltaTime, 0f);
            });
        }
    }
    
    image

    Job System Overview

    • Sepreate data from function
    • Multi-core processing
    • Save multi-threading

    Job Sytem Benefits

    Average core count increasing

    • Mainstream CPUs 4~6 physical cores, 8-12 logical
    • Enthusiast CPUs up to 16 physical, 32 logical
      Moste cores go unused
      Multithreading problems
    • Thread safe code is difficult
    • Race condintions 代码安全
    • Context switching is expensive
      Solution
    • Job System manage this for you
    • Focus entirely on your game specific code

    相关文章

      网友评论

          本文标题:Unity ECS JobSystem BurstCompile

          本文链接:https://www.haomeiwen.com/subject/fmqvbqtx.html