Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

EntityCommandBuffer AddComponent with IBufferElementData

Discussion in 'Entity Component System' started by redwren, Apr 8, 2021.

  1. redwren

    redwren

    Joined:
    Aug 2, 2019
    Posts:
    69
    I have some component data that is usually stored as a buffer element, but I was writing a new system that copies one of the elements onto another entity as a component. My first pass used EntityManager.AddComponent, which seemed to work fine. Switching this to use an EntityCommandBuffer caused an issue, because EntityCommandBuffer#AddComponent requires the component type to implement IComponentData, and components can't implement both IComponentData and IBufferElementData. Is there a way around this without creating a wrapper type? Or do I need to have both "T" and TBufferElement" types if I plan on using the same data in both ways?
     
  2. Antypodish

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    10,754
    Entities can have multiple components and buffers.
    But not buffers in components.
     
    MNNoxMortem likes this.
  3. redwren

    redwren

    Joined:
    Aug 2, 2019
    Posts:
    69
    I'm talking about something else. Some code will clarify:

    Code (CSharp):
    1. public struct SomeData : IBufferElementData { ... }
    2.  
    3. public class SomeSystem : SystemBase
    4. {
    5.   protected override void OnUpdate()
    6.   {
    7.     EntityCommandBuffer ecb = ... // get the command buffer from somwhere
    8.  
    9.     var e1 = ecb.CreateEntity();
    10.     var e2 = ecb.CreateEntity();
    11.    
    12.     // This works as intended obviously.
    13.     ecb.AddBuffer<SomeData>(e1);
    14.  
    15.     // This does not work, because SomeData is not IComponentData
    16.     ecb.AddComponent<SomeData>(e2);
    17.   }
    18. }
    One work around is to create a wrapper type for IBufferElementData (or for IComponentData, same thing):

    Code (CSharp):
    1. public struct SomeData : IComponentData
    2. {
    3.   ...
    4. }
    5.  
    6. public struct SomeDataAsBufferElement : IBufferElementData
    7. {
    8.   public SomeData Value;
    9. }
    10.  
    I'm wondering if there is a better approach for data that is stored as both a component and as a buffer element. Creating a wrapper type works, and reinterpreting the buffer helps, but it's still type noise. What initially threw me off is that EntityManager does not prevent you from treating IBufferElementData as IComponentData, only EntityCommandBuffer does.