天天看點

Unity ECS技術開發HelloWorld

ECS三要素

元件、系統、管理器

在2018環境下的ECS環境配置

學習ECS項目,需要導入5個包

Entities

Mathematics 數學

Hybrid Render 混合渲染

Jobs

Burst

簡單的ECS項目隻需要安裝前三個插件(我使用的是2018.4.34f1)

Unity ECS技術開發HelloWorld

18版本HelloWorld

讓一個cube在場景中旋轉起來。

在場景中制作一個紅色的Cube,并為它添加元件和系統兩個腳本。RotationCubeComponent.cs和RotationCubeSystem.cs

RotationCubeComponent.cs

/***
 *  使用Unity2018.4版本 開發ECS的HelloWorld
 *
 *  定義ECS的"元件"  元件隻有資料 沒有方法
 */

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RotationCubeComponent : MonoBehaviour
{
    /// 旋轉速度
    public float speed;
}      

RotationCubeSystem.cs

/***
 *  使用Unity2018.4版本 開發ECS的HelloWorld
 *
 *  定義ECS的"系統" 隻有方法沒有資料
 */

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.Entities; // 引入命名空間

// 抽象方法
public class RotationCubeSystem : ComponentSystem
{
    struct Group
    {
        public RotationCubeComponent rotation;
        public Transform transform;
    }

    protected override void OnUpdate()
    {
        // GetEntities 2018所有 2019被廢棄
        foreach (var en in GetEntities())
        {
            // 進行旋轉
            en.transform.Rotate(Vector3.down, en.rotation.speed * Time.deltaTime);
        }
    }
}      

RotationCubeComponent.cs繼承MonoBehaviour可以直接拖拽到Cube上,但是系統無法添加到cube上。

此時需要添加Entities系統腳本Game Object Entity,可以把這個腳本當作管理腳本,把元件和系統關聯起臉,放Cube可以運作起來。

Unity ECS技術開發HelloWorld

在這個HelloWorld裡,建立了兩個腳本

繼承MonnoBehaviour,内部定義Cube的旋轉速度。

RotationCubeSystem.cs

繼承ComponetSystem,定義Group的結構體,然後再OnUpdate()中使用foreach循環讓Cube旋轉。

GameObjectEntity.cs

屬于Entitys命名空間中的内置腳本,作用是吧“元件”和“系統”結合起來

通過Demo回看ECS

下圖是Unity官方的關于ECS的整體架構核心示意圖。

Unity ECS技術開發HelloWorld