Search Unity

Grab a Component by Type within a Job

Discussion in 'Entity Component System' started by TheGabelle, May 21, 2020.

  1. TheGabelle

    TheGabelle

    Joined:
    Aug 23, 2013
    Posts:
    242
    I'm trying to build a Stat - Affect system. My first attempt was a unique system, component, and affect buffer for each stat, but it smelled like a bad design. So, I thought maybe I could use a single dynamic buffer of affects where each affect holds a reference to whichever stat component it should modify. I'm unsure if there's a proper way to do something akin to the code below, or if it's a bad idea:
    Code (CSharp):
    1. public struct Health : IComponentData
    2. {
    3.     public int Value;
    4.     public int MaxValue;
    5. }
    6.  
    7. // unknown number of other stats with same fields
    8.  
    9. public struct StatAffect : IBufferElementData
    10. {
    11.     public Type TargetComponent;
    12.     public int Value;
    13.     public int Iterations;
    14.     public float Delay;
    15.     public float Time;
    16. }
    17.  
    18. public class StatAffectSystem : SystemBase
    19. {
    20.     protected override void OnUpdate ()
    21.     {
    22.         // [NativeDisableParallelForRestriction]  
    23.         Entities.ForEach( (Entity entity, DynamicBuffer<StatAffect> statAffectBuffer) => {
    24.            
    25.             foreach (var statAffect in statAffectBuffer)
    26.             {
    27.                 // get some Entity component using statAffect.TargetComponent
    28.                 // logic to modify component
    29.                 // write to component with updated values
    30.             }
    31.         })
    32.         .ScheduleParallel();
    33.     }
    34. }
     
  2. TheGabelle

    TheGabelle

    Joined:
    Aug 23, 2013
    Posts:
    242
    No idea why there's a duplicate thread. Let's use this one.