ECS入门 1.ForEach
前言
此示例演示了一个旋转实例,多维数据集的简单 ECS 系统。
它显示了什么?
此示例演示了 ECS 中数据和功能的分离。数据存储在组件中,而功能写入系统。
RotationSpeedSystem_ForEach使用存储在RotationSpeed_ForEach组件中的数据更新和旋转。
Systems 和 Entities.ForEach
RotationSpeedSystem_ForEach是从系统库派生的系统,它使用实体。此示例仅创建单个实体,但如果向场景中添加了更多实体,则RotationSpeedSystem_ForEach更新所有实体 - 只要它们具有RotationSpeed_ForEach组件(以及在将游戏对象的转换转换为 ECS 组件时添加的旋转Rotation组件)。
请注意,如果有多个块,则使用实体系统使用计划并行来调度 lambda 表达式在多个工作线程上运行。如果多个内核可用(并且您的数据跨多个块),这会自动利用它们。
Tip:
Entities.ForEach提供了自己的机制来定义用于选择要处理的实体的实体查询。查询会自动包含您用作 lambda 函数参数的任何组件。您还可以使用WithAll、WithAny和WithNone子句进一步细化选定的实体。
Converting from GameObject to Entity
此示例使用自动生成的创作组件。 此单行为是通过IComponentData上的GenerateAuthoringComponent属性创建的,并公开该类型的所有公共字段以进行创作。
ForEach项目
场景布置
创建两个Cube其中一个作为父物体,并勾选Inspector面板上的ConvertToEntity

代码编写
创建两个脚本
RotationSpeed_ForEach.cs
using System;
using Unity.Entities;
// ReSharper disable once InconsistentNaming 重新共享器禁用一次不一致的命名
// 添加可以在 Unity Editor 中显示出来的属性
[GenerateAuthoringComponent]
public struct RotationSpeed_ForEach : IComponentData
{
/// <summary>
/// 旋转速度
/// </summary>
public float RadiansPerSecond;
}
RotationSpeedSystem_ForEach.cs
using Unity.Entities;
using Unity.Jobs;
using Unity.Mathematics;
using Unity.Transforms;
// This system updates all entities in the scene with both a RotationSpeed_ForEach and Rotation component.
// 此系统使用RotationSpeed_ForEach和旋转组件更新场景中的所有实体。
// ReSharper disable once InconsistentNaming
// 重新共享器禁用一次不一致的命名
public partial class RotationSpeedSystem_ForEach : SystemBase
{
// OnUpdate runs on the main thread.
// 更新在主线程上运行。
protected override void OnUpdate()
{
float deltaTime = Time.DeltaTime;
// Schedule job to rotate around up vector
// 计划并行作业以围绕向上矢量旋转
Entities
// 1.将指定的字符串指定为生成的作业类的名称
.WithName("RotationSpeedSystem_ForEach")
// 2.遍历所有带有Rotation组件和RotationSpeed_ForEach组件的Entity
.ForEach((ref Rotation rotation, in RotationSpeed_ForEach rotationSpeed) =>
{
rotation.Value = math.mul(
math.normalize(rotation.Value),
quaternion.AxisAngle(math.up(), rotationSpeed.RadiansPerSecond * deltaTime));
})
.ScheduleParallel();
}
}
添加并设置脚本
给父物体添加RotationSpeed_ForEach脚本,并设置Radians Per Second的值为2

保存场景并运行
总结
Entity
使用ConvertToEntity转换GameObject而成
Component
RotationSpeed_ForEach
System
RotationSpeedSystem_ForEach
运行效果


825

被折叠的 条评论
为什么被折叠?



