介绍完ECS的大致理念之后,我们接着单独来了解下Entity,Component和System的概念以及使用,首先我们先从Entity开始入手。
Entity概念
我们来看下Entity的组成,代码如下,只有Index和Version两个字段。
public struct Entity
{
/// <summary>
/// The ID of an entity.
/// </summary>
public int Index;
public int Version;
}
我们可以理解为Entity就是游戏中不同的物体,其中只有一个ID,也就是Index用来进行区分。Entity中不存在任何数据和行为,这些交给了Component和System去办了。
在每个World中,会有一个EntityManager来管理该World下所有的Entity,EntityManager利用NativeArray来管理Entities并且纪录了每个Entity和Component的关系。
World
我们可以将其理解成一种Manager,每一个World都拥有一个EntityManager和一系列的System,我们可以自由的创建World:
World newWorld = new World("NewWorld");
ECS中会有一个默认的World(DefaultWorld),可以通过 World.DefaultGameObjectInjectionWorld 来获取它。系统自带的System和我们自定义的System默认都会被添加进这个World。
创建Entity
创建一个Entity
前面我们说到Entity是由EntityManager来管理的,而EntityManager又存放与World之中,因此要创建Entity,我们先要获得EntityManager,然后就可以利用其CreateEntity方法来创建我们的Entity了。
EntityManager entityManager = World.DefaultGameObjectInjectionWorld.EntityManager;
Entity entity = mEntityManager.CreateEntity();
若要为Entity添加组件,也需要使用EntityManager来完成,例如添加一个用于存放座标信息的Translation Component并且赋值:
entityManager.AddComponentData(entity, new Translation(){Value = new float3(0, 0, 0)});
若要删除Entity上的Component,自然是要用RemoveComponent方法了:
entityManager.RemoveComponent<Translation>(entity);
除此之外,我们也可以在创建的时候就指定好需要添加的组件,然后再利用 SetComponentData 赋值,例如:
Entity entity = entityManager.CreateEntity(typeof(Translation), typeof(OtherComponent), ...);
entityManager.SetComponentData(entity, new Translation(){Value = new float3(0, 0, 0)});
前面我们提到Component的不同组合被称为Archetype,因此我们也可实现声明好Archetype,然后用其创建Entity,这样生成的Entity就会带有Archetype所代表的所有Component(其实和上面那种方法是等价的)。
EntityArchetype entityArchetype = entityManager.CreateArchetype(typeof(Translation), typeof(LocalToWorld), typeof(RenderMesh));
Entity entity = entityManager.CreateEntity(entityArchetype);
entityManager.SetComponentData(entity, new Translation(){Value = new float3(0, 0, 0)});
对于已存在的Entity,我们可以使用EntityManager.Instantiate方法来进行copy
Entity entity2 = entityManager.Instantiate(entity);
创建多个Entity
CreateEntity不仅可以创建一个Entity,也可以同时创建多个Entity,前提是要事先声明好EntityArchetype,例如
NativeArray<Entity> entityArray = new NativeArray<Entity>(10, Allocator.Temp);
entityManager.CreateEntity(entityArchetype, entityArray);
entityArray.Dispose();
等价于
entityManager.CreateEntity(entityArchetype, 10, Allocator.Temp).Dispose();;
对于已存在的Entities我们可以进行整体copy,Entities中的数据都会被copy到新的Entities中。
NativeArray<Entity> copyEntityArray = new NativeArray<Entity>(10, Allocator.Temp);
entityManager.Instantiate(entityArray, copyEntityArray);
copyEntityArray.Dispose();
Instantiate也可将单个Entity进行多份copy
entityManager.Instantiate(entity, 10, Allocator.Temp);
销毁Entity
entityManager.DestroyEntity(entity);