此示例演示了一个简单的ECS系统,它可以旋转一对立方体。

它显示了什么?

此示例演示了ECS中数据和功能的分离。
数据存储在组件中,如下RadiansPerSecond属性存储在RotationSpeed_ForEach组件中, 该结构体数据组件有[Serializable]修饰符,表示实例化属性。

using System;

using Unity.Entities;

// Serializable attribute is for editor support.

[Serializable]

public struct RotationSpeed_ForEach : IComponentData

{
     public float RadiansPerSecond;

}

而功能则写入系统,如下RotationSpeedSystem_ForEach 使用存储在 RotationSpeed_ForEach 组件中的data更新对象的旋转。

using Unity.Entities;

using Unity.Mathematics;

using Unity.Transforms;

using UnityEngine;

// This system updates all entities in the scene with both a RotationSpeed_ForEach and Rotation component.

public class RotationSpeedSystem_ForEach : ComponentSystem

{
     protected override void OnUpdate()
     {
         // Entities.ForEach processes each set of ComponentData on the main thread. This is not the recommended
         // method for best performance. However, we start with it here to demonstrate the clearer separation
         // between ComponentSystem Update (logic) and ComponentData (data).
         // There is no update logic on the individual ComponentData.
         Entities.ForEach((ref RotationSpeed_ForEach rotationSpeed, ref Rotation rotation) =>
         {
             var deltaTime = Time.deltaTime;
             rotation.Value = math.mul(math.normalize(rotation.Value),
                 quaternion.AxisAngle(math.up(), rotationSpeed.RadiansPerSecond * deltaTime));
         });
     }

}

ComponentSystems和Entities.ForEach

RotationSpeedSystem_ForEach是一个ComponentSystem,它使用Entities.ForEach委托来遍历实体。
此示例仅创建单个实体,但如果向场景添加了更多实体,则RotationSpeedSystem_ForEach会更新所有实体 - 只要它们具有RotationSpeed_ForEach组件(并且在将GameObject的Transform转换为ECS组件时添加了旋转组件)。
请注意,使用Entities.ForEach的ComponentSystems在主线程上运行。
要利用多个内核,可以使用JobComponentSystem(如下一个HelloCube示例所示)。

从GameObject转换为Entity

ConvertToEntity MonoBehaviour在Awake时将GameObject及其子节点转换为实体和ECS组件。
目前,ConvertToEntity可以转换的内置Unity MonoBehaviours集包括Transform和MeshRenderer。
您可以使用实体调试器(菜单:窗口> 分析> 实体调试器)来检查转换创建的ECS实体和组件。
您可以在自己的MonoBehaviours上实现IConvertGameObjectEntity接口,以提供ConvertToEntity用于将存储在MonoBehavi中的数据转换为ECS组件的转换函数。
在此示例中, RotationSpeedAuthoring_ForEach MonoBehaviour使用IConvertGameObjectEntity在转换时将RotationSpeed_ForEach组件添加到实体。

using System;

using Unity.Entities;

using Unity.Mathematics;

using UnityEngine;

[RequiresEntityConversion]

public class RotationSpeedAuthoring_ForEach : MonoBehaviour, IConvertGameObjectToEntity

{
     public float DegreesPerSecond;

// The MonoBehaviour data is converted to ComponentData on the entity.
     // We are specifically transforming from a good editor representation of the data (Represented in degrees)
     // To a good runtime representation (Represented in radians)
     public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
     {
         var data = new RotationSpeed_ForEach { RadiansPerSecond = math.radians(DegreesPerSecond) };
         dstManager.AddComponentData(entity, data);
     }

}


HelloCube_1b_ForEachWithEntityChanges

此示例演示了一个简单的ECS系统,该系统使用查询来选择要更新的正确实体集。然后它在ForEach lambda函数内部修改这些实体。

该示例定义了两个标记组件,名为MovingCube_ForEachWithEntityChanges和MoveUp_ForEachWithEntityChanges。

using System;
using Unity.Entities;

namespace Samples.HelloCube_1b
{
    // Serializable attribute is for editor support.
    [Serializable]
    public struct MoveUp_ForEachWithEntityChanges : IComponentData
    {
        // MoveUp is a "tag" component and contains no data. Tag components can be used to mark entities that a system should process.
    }
}

using System;
using Unity.Entities;

namespace Samples.HelloCube_1b
{
    // Serializable attribute is for editor support.
    [Serializable]
    public struct MovingCube_ForEachWithEntityChanges : IComponentData
    {
        // MovingCube_ForEachWithEntityChanges is a "tag" component and contains no data.
        // Tag components can be used to mark entities that a system should process.
    }
}

系统中的一个查询选择同时具有MoveUp_ForEachWithEntityChanges组件和Translation组件的所有实体。与此查询关联的ForEach lambda函数向上移动每个选定的实体,直到达到某个高度时,该函数将删除MoveUp_ForEachWithEntityChanges组件,以便下次系统更新时,将不会选择该实体,因此它不会向上移动任何更远的位置。

第二个查询选择具有Translation组件但没有MoveUp_ForEachWithEntityChanges组件的所有实体。与第二个查询关联的ForEach函数将实体向下移动到其起始位置,并添加新的MoveUp_ForEachWithEntityChanges组件。由于实体再次具有MoveUp_ForEachWithEntityChanges组件,因此下次系统更新时,实体将被第一个ForEach函数向上移动并被第二个查询跳过。

MovingCube_ForEachWithEntityChanges是一个标记组件,用于确保系统仅适用于为此示例标记的组件。示例中的两个查询都需要MovingCube_ForEachWithEntityChanges组件。

它显示了什么?

此示例演示了一个简单的ECS系统,该系统使用查询来选择要向上移动的一组实体。当它们达到一定高度时,系统会删除一个组件并使用另一个查询在较低的高度重新生成它们。它还演示了使用“标签”组件来提供选择具有待处理标记组件的特定entite组的方法。最后,此示例演示了如何在ForEach lambda函数内修改实体。

组件系统和实体.ForEach

MovementSystem_ForEachWithEntityChanges是一个ComponentSystem,它使用Entities.ForEach lambda函数迭代实体。此示例使用WithAll和WithNone约束来选择要处理的特定实体集。

using Unity.Entities;

using Unity.Mathematics;

using Unity.Transforms;

using UnityEngine;

namespace Samples.HelloCube_1b

{
     // This system updates all entities in the scene with Translation components.
     // It treats entities differently depending on whether or not they also have a MoveUp component.
     public class MovementSystem_ForEachWithEntityChanges : ComponentSystem
     {
         protected override void OnUpdate()
         {
             // If a MoveUp component is present, then the system updates the Translation component to move the entity upwards.
             // Once the entity reaches a predetermined height, the function removes the MoveUp component.
             Entities.WithAllReadOnly<MovingCube_ForEachWithEntityChanges, MoveUp_ForEachWithEntityChanges>().ForEach(
                 (Entity id, ref Translation translation) =>
                 {
                     var deltaTime = Time.deltaTime;
                     translation = new Translation()
                     {
                         Value = new float3(translation.Value.x, translation.Value.y + deltaTime, translation.Value.z)
                     };

if (translation.Value.y > 10.0f)
                         EntityManager.RemoveComponent<MoveUp_ForEachWithEntityChanges>(id);
                 }
             );

// If an entity does not have a MoveUp component (but does have a Translation component),
             // then the system moves the entity down to its starting point and adds a MoveUp component.
             Entities.WithAllReadOnly<MovingCube_ForEachWithEntityChanges>().WithNone<MoveUp_ForEachWithEntityChanges>().ForEach(
                 (Entity id, ref Translation translation) =>
                 {
                     translation = new Translation()
                     {
                         Value = new float3(translation.Value.x, -10.0f, translation.Value.z)
                     };

EntityManager.AddComponentData(id, new MoveUp_ForEachWithEntityChanges());
                 }
             );
         }
     }

}

注意:使用Entities.ForEach的组件系统在主线程上运行。要利用多个内核,可以使用JobComponentSystem(如其他HelloCube示例所示)。这也允许更改ForEach lambda函数内的实体。

HelloCube:ForEach的更多相关文章

  1. Java:foreach实现原理

    第一部分: For-each Loop Purpose The basic for loop was extended in Java5 to make iteration over arrays a ...

  2. 编写高质量代码改善C#程序的157个建议——建议18:foreach不能代替for

    建议18:foreach不能代替for 上一个建议中提到了foreach的两个优点:语法更简单,默认调用Dispose方法,所有我们强烈建议在实际的代码编写中更多的使用foreach.但是,该建议也有 ...

  3. (JavaScript基础向)日常小发现:forEach等函数的第二个参数的用法

    forEach函数用得平时用得比较多,但是从来没想到forEach函数还有第二个参数. 这里是菜鸟教程对forEach函数的详细说明:forEach的详细说明. 如上图,forEach函数有第二个参数 ...

  4. C#:foreach语句,yield语句

    原文:C#:foreach语句,yield语句 1. foreach语句 C#编译器会把foreach语句转换为IEnumerable接口的方法和属性. foreach (Person p in pe ...

  5. 如何让类数组也使用数组的方法比如:forEach()

    思路: 让类数组绑定数组的方法<div>1</div><div>2</div>方法一: let div = document.getElementsBy ...

  6. Qt:foreach

    0.说明 Qt提供一个关键字foreach(实际上是<QtGlobal>中定义的一个宏)用于方便地访问容器中的所有数据项. foreach关键字用于遍历容器中的所有数据项 注意 forea ...

  7. php学习笔记:foreach循环访问关联数组里的值

    foreach循环可以将数组里的所有值都访问到,下面我们展示下,用foreach循环访问关联数组里的值. 例如: $fruit=array('apple'=>"苹果",'ba ...

  8. 第46条:for-each循环优先于传统的for循环

    for-each循环通过完全隐藏迭代器或者索引变量,避免混乱和出错的可能,适用于集合和数组和任何实现Iterable接口的对象. 使用传统for循环,容易出错: enum Face { ONE, TW ...

  9. 空数组在以下三种遍历中均不可更改:forEach、map和for...in

    首先,我们要知道对于forEach.map和for...in三种遍历,在不是空数组的情况下,要想实现更改原数组的方法,代码如下: var list = [1,2,3,4]; var list1 = [ ...

随机推荐

  1. Jsp与JavaScript区别

    有时候会误以为这两个是同一个概念,但其实不是 Jsp全名为Java Server Pages(Java服务器页面),其根本是一个简化的Servlet设计,他实现了在Java当中使用HTML标签.Jsp ...

  2. Oracle-锁的查询和处理

    1.查出锁定object的session的信息以及被锁定的object名 SELECT L.SESSION_ID SID, S.SERIAL#, L.LOCKED_MODE, L.ORACLE_USE ...

  3. Spring MVC + freemarker实现半自动静态化

    这里对freemarker的代码进行了修改,效果:1,请求.do的URL时直接生成对应的.htm文件,并将请求转发到该htm文件2,自由控制某个页面是否需要静态化原理:对org.springframe ...

  4. combogrid下拉方法封装

    //html <input id="addxxxxx" name="xxxxxx" style="width:380px;height:36px ...

  5. axios并行请求

    有些操作需要在几个异步请求都完成之后再执行,虽然一个Ajax可以放到另一个Ajax完成的回调里面,但这样很容易导致回调地狱,且代码也极其不美观. 幸运的是axios提供了并行请求的方法, 使用方法: ...

  6. C#中'??'符的使用

    ??  用于判断当前对象是否为null. 语法: 对象 ?? "当前对象为null时赋的默认值". string nullString = null; string Kong = ...

  7. final详解

    final的含义? final:java中的关键字,意为“终态的”或者“无法改变的”.可用来修饰类.变量.方法. 变量(成员变量.静态变量.局部变量) 注意: 1.final变量即为常量,通常常量名大 ...

  8. 【基本算法入门-字符串哈希(Hash)】-C++

    字符串哈希入门 说得通俗一点,字符串哈希实质上就是把每个不同的字符串转成不同的整数. 为什么会有这样的需要呢?很明显,存储一个超长的字符串和存储一个超大但是能存的下的整数,后者所占的空间会少的多,但主 ...

  9. 012_Linux驱动之_wait_event_interruptible

    1. 首先这篇博客讲解得挺好的,推荐 wait_event_interruptible 使用方法 2 .函数原型: #define wait_event_interruptible(wq, condi ...

  10. MySQL 中索引的长度的限制

    单列索引的长度的限制 (5.6里面默认不能超过767bytes,5.7不超过3072bytes): 起因是256×3-1=767.这个3是字符最大占用空间(utf8).但是在5.5以后,开始支持4个字 ...