前言 
此示例演示了一个旋转实例,多维数据集的简单 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;
[GenerateAuthoringComponent]
public struct RotationSpeed_ForEach : IComponentData
{
    
    
    
    public float RadiansPerSecond;
}
  
RotationSpeedSystem_ForEach.cs  
using Unity.Entities;
using Unity.Jobs;
using Unity.Mathematics;
using Unity.Transforms;
public partial class RotationSpeedSystem_ForEach : SystemBase
{
    
    
    protected override void OnUpdate()
    {
        float deltaTime = Time.DeltaTime;
        
        
        Entities
            
            .WithName("RotationSpeedSystem_ForEach")
            
            .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  
运行效果 
  
                
                
                
        
        
    
  
 
 |