Search Unity

Question Calling SetComponent or GetComponent from a function in Entities.ForEach

Discussion in 'Entity Component System' started by slushieboy99, Dec 13, 2022.

  1. slushieboy99

    slushieboy99

    Joined:
    Aug 29, 2014
    Posts:
    88
    I wrote the following function and want to be able to call it from Entities.Foreach:

    Code (CSharp):
    1. private void AssignTarget(Entity e, Entity target, EntityCommandBuffer ecb){
    2.         TargetComponent targetComp = new TargetComponent{
    3.                         target = target,
    4.         };
    5.         ecb.AddComponent<TargetComponent>(e, targetComp);
    6.  
    7.         NumAttackingComponent targetNum = GetComponent<NumAttackingComponent>(target);
    8.         targetNum.numAttacking += 1;
    9.         SetComponent<NumAttackingComponent>(target, targetNum);
    10.     }
    The issue is I get an error about non-valued 'this'. I'd like to make functions for bits of code I reuse often that mirror Entities.Foreach code, and then only use them in Entities.Foreach. Is this possible or do I need to pass in an EntityManager or something of the sort?
     
  2. Spy-Master

    Spy-Master

    Joined:
    Aug 4, 2022
    Posts:
    581
    You generally can't use any instance members in Entities.ForEach, so you would have to use static methods and pass in something that would get you access to GetComponent / SetComponent, so either the EntityManager or ComponentLookup (on 1.0 exp/preview, or ComponentDataFromEntity on previous). Personally, I would say the better design would be using ComponentLookup, which would allow you to reuse these across IJobEntity and Entities.ForEach with no consequences.
     
  3. slushieboy99

    slushieboy99

    Joined:
    Aug 29, 2014
    Posts:
    88
    I should have mentioned I am looking to do this exclusively with static functions. Thanks for the info! I figured that would be the case. GetComponent calls ComponentDataFromEntity, so the runtime should be similar between the two implementations, correct?
     
  4. Spy-Master

    Spy-Master

    Joined:
    Aug 4, 2022
    Posts:
    581
    Yeah, they should be similar with how the codegen for Entities.ForEach works out (I believe it just injects a ComponentLookup for the SystemBase.Get/SetComponent calls).