Search Unity

Feature Request Support [Optional] for DynamicBuffer<T> fields in Aspects

Discussion in 'Entity Component System' started by Enderlook, May 7, 2023.

  1. Enderlook

    Enderlook

    Joined:
    Dec 4, 2018
    Posts:
    50
    The attribute `[OptionalAttribute]` seems to be ignored in fields that reference dynamic buffers in aspects.
    This makes quite frustrating to work with aspects when you want to optionally include a dynamic buffer.
     
    FaithlessOne likes this.
  2. macoson

    macoson

    Joined:
    Oct 12, 2020
    Posts:
    4
    You can implement Optional DynamicBuffer on Aspect using Enableable feature here is example I've tested:

    Code (CSharp):
    1. public struct  UnitOnTile: IBufferElementData, IEnableableComponent{
    2.         public Entity Value;
    3. }
    4. public override void Bake(TileAuthoring authoring){
    5.         var entity = GetEntity(TransformUsageFlags.Dynamic);
    6.         AddBuffer<UnitOnTile>(entity);
    7.         SetComponentEnabled<UnitOnTile>(entity, true);  // or false
    8. }
    9. public readonly partial struct TileAspect : IAspect{
    10.         [Optional] // or not
    11.         readonly DynamicBuffer<UnitOnTile> _unitsOnTile;
    12. }
    13. // Spawn 400 Tiles by another system
    14. TestSystem.OnUpdate(){
    15.         int i = 0;
    16.         foreach (TileAspect tile in SystemAPI.Query<TileAspect>()){
    17.                 i++;}
    18.         Debug.Log("SystemAPI.Query<TileAspect>() count:" + i);
    19.  
    20.         int j = 0;
    21.         foreach (var tile in SystemAPI.Query<DynamicBuffer<UnitOnTile>>()){
    22.                 j++;}
    23.         Debug.Log("SystemAPI.Query<DynamicBuffer<UnitOnTile>> count:" + j);
    24. }
    Output:
     
    Last edited: May 28, 2023
  3. Enderlook

    Enderlook

    Joined:
    Dec 4, 2018
    Posts:
    50
    Thanks for the reply, but that is making the buffer enabeable, not actually making it optional in the aspect.
    This means, not only that the chunk will internally track if the buffer is enabled or not in the underlying implementation of DOTS (which may or may not increase memory consumption and CPU cost in other tasks, no idea), but this requires adding an `IEnableableComponent` to the buffer element type, so if I'm not the owner of that type, then I can't make it optional in the aspect. So I can for example put optional buffers from third-party libraries over which I have no control in their source code.