As the header, I wanna write a BagComponent which contains a list of Entities and some common properties like CurrentWeight,MaxWeight,CurrentCount,MaxCount etc.(With pure ECS)
Dynamic buffers should be helpful.
using Unity.Entities;
public struct Bag : IComponentData
{
public int CurrentWeight;
public int MaxWeight;
public int CurrentCount;
public int MaxCount;
}
using Unity.Entities;
[InternalBufferCapacity(16)]
public struct BagBufferElement : IBufferElementData
{
public Entity Entity;
public static implicit operator Entity(BagBufferElement e) => e.Entity;
public static implicit operator BagBufferElement(Entity e) => new BagBufferElement { Entity = e };
}
var bag = EntityManager.CreateEntity(typeof(Bag));
EntityManager.AddBuffer<BagBufferElement>(bag);
Wow, thank you so much!
And is there anyway to store the buffer and common properties in a single component?
Not at the moment. What you can do is prepare an Entity that has the DynamicBuffer then use this entity as reference to the owner component. For example:
// This is the bag entity
Entity bag = EntityManager.CreateEntity(typeof(Bag));
EntityManager.AddBuffer<BagBufferElement>(bag);
// This is the owner component
struct Character : IComponentData {
public Entity bagEntity;
}
Entity characterEntity = EntityManager.CreateEntity(typeof(Character));
// Prepare the component
Character character = new Character() {
bagEntity = bag
};
EntityManager.SetComponentData(characterEntity, character);