DOTS 是未来游戏行业的趋势,面向数据编程使场景中存在许多游戏物体还可以保持高性能,目前部分游戏已经使用这种方式。而在2023年1.0版本的发布,面向数据编程正在逐渐走向成熟,于是我选择进行学习。
配置ECS DOTS
Unity 编辑器版本为:2020.3.40
打开Window-PackageManager,点击右上角加号选择Add package from git URL
添加Burst Jobs Collections Entities Mathematics Hybird Renderer(添加Entities 之后除Hybird Renderer其他会自动安装,但是为了保险起见建议手动添加)
其中预览包
com.untiy.entities
com.unity.burst
com.unity.jobs
com.unity.collections
com.unity.mathematics
com.unity.rendering.hybrid
添加完毕后即可进行DOTS的编程了
ECS的组成
ECS由三部分组成 实体(Entitiy) 组件(Component)系统(System)
1.Component
是纯数据,不含任何逻辑行为
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.Entities;
public struct LevelCompent : IComponentData
{
public float level;
}
2.System
主要逻辑所在,根据Entites 和Components 编写对应的逻辑
通过ForEach()来对Entity上的数值进行编辑。
using Unity.Entities;
using Unity.Transforms;
using Unity.Mathematics;
public class MoveSystem : ComponentSystem
{
protected override void OnUpdate()
{
Entities.ForEach((ref MoveSpeedComponent moveCmpt ,ref Translation translation,ref Rotation rotation) =>
{
translation.Value.x += moveCmpt.mMoveSpeed * Time.DeltaTime;
if (translation.Value.x>30)
{
rotation.Value=quaternion.Euler(new float3(0,130,0));
moveCmpt.mMoveSpeed = -math.abs(moveCmpt.mMoveSpeed);
}
else if (translation.Value.x < -30)
rotation.Value = quaternion.Euler(new float3(0, -130, 0));
moveCmpt.mMoveSpeed =math.abs(moveCmpt.mMoveSpeed);
}
});
}
}
3.Entity
Entity即为启动类,所有的数据将在此纪录我们可以在Inspector面板上看到组件
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.Entities;
using Unity.Transforms;
using Unity.Collections;
using Unity.Rendering;
public class Testing : MonoBehaviour
{
[SerializeField] private Mesh mesh;
[SerializeField] private Material material;
private void Start()
{
EntityManager entityManager = World.DefaultGameObjectInjectionWorld.EntityManager;
EntityArchetype entityArchetype = entityManager.CreateArchetype(
typeof(LevelCompent),
typeof(Translation),
typeof(RenderMesh),
typeof(LocalToWorld),
typeof(RenderBounds)
);
NativeArray<Entity> entityArray = new NativeArray<Entity>(1, Allocator.Temp);
entityManager.CreateEntity(entityArchetype, entityArray);
for (int i = 0; i < entityArray.Length; i++)
{
Entity entity = entityArray[i];
entityManager.SetComponentData(entity, new LevelCompent { level = Random.Range(10, 20) });
entityManager.SetSharedComponentData(entity, new RenderMesh
{
mesh = mesh,
material = material
});
}
entityArray.Dispose();
}
}
最后即便有如此多的单位,帧率也可以打到40FPS左右
学习教程:Unity 2019 新框架 ECS入门
参考博客:铸梦xy的博客