Search Unity

How do you handle references in ECS?

Discussion in 'Scripting' started by Afropenguinn, Mar 26, 2020.

  1. Afropenguinn

    Afropenguinn

    Joined:
    May 15, 2013
    Posts:
    305
    Trying to wrap my head around ECS, and I'm confused as to how you would handle references. Components are structs, and from the material I've went through they advise against storing refs in components. So how would you store a reference to other components? Or, is there some design pattern I'm not understanding that doesn't involve storing references?

    EDIT: To clarify, I mean references to components in other entities.
     
  2. Antypodish

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    10,778
    If is common data for group of entities, you can use shared component data. SCD.

    Otherwise, you need reference to entity, containing relevant components.

    So for example you got thousands of bullets flying, and chacking for collision with a target. When collide, get target entity health component, and subtract health.

    There is many ways of course, how you can do that.

    What exactly you try to do?
     
  3. Afropenguinn

    Afropenguinn

    Joined:
    May 15, 2013
    Posts:
    305
    Oh, I'll have to read up more on SCD, so far I've only used it for rendering purposes!

    And I was thinking something like:
    You have a group of pawns that want to attack each other
    Each pawn will create a worker thread to decide a target based on a list of criteria
    Once a target is decided, each pawn needs a reference to its target so it can move towards it and attack, as well as change up its tactics if its target moves around.

    So each pawn would need a ref to another pawn component, or more than likely, a ref to the their target's entity so it can base its tactics off of their target's position, remaining health, ect.
     
  4. Antypodish

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    10,778
    In such case like health and position, SCD wont be of use, since each pawn has own data.
    Nstead, you need take approach, of finding target entity.

    Simplest but least performant is iterate array of each entity by each entity and check lts sy distance.

    Another option is using hash map, see boids example.

    You can also build octree/quadtree or other spatial mapping, to find nearest, or raycast for target entity.

    And also, you can utilise Unity.physics, to get target entity.

    Once you got target entity, you use for example GetComponentWithEntity.
    In such way, you can run jobs in parallel. Be careful however, when doing so, whe each by each entity is involved, to avoid potential race conditions.