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

Question Best Approach for a NativeHash that needs multiple entries?

Discussion in 'Entity Component System' started by Enoch, Oct 14, 2020.

  1. Enoch

    Enoch

    Joined:
    Mar 19, 2013
    Posts:
    198
    My use case is a 2d map referenced by int2. I need to store an entity reference at a given position on the map so I would normally use a NativeHashMap<int2, Entity>. I do this for fast lookup(O(1)). However I want to support multiple entities per location. I would really need something like NativeHashMap<int2, NativeArray<Entity>> but we can't do that.

    So as alternate I was thinking about a shared component that would be attached to these Entities ie:
    struct MapLocation : ISharedComponentData
    {
    public int2 location;
    }

    This would allow me to use an EntityQuery with a filter applied. I think this would be fast possibly a good alternative but it will mean 100s maybe 1000s of entities that have different MapLocations (SharedComponentData). That means 100s or 1000s of archetypes. I am not sure that this won't have even more issues. Maybe its better if I just do the O(n^2) comparison (all map locations versus all moving items that need to check all map locations). However if adding a ISharedComponentData is more like indexing a database, I certainly wouldn't think twice about doing this.

    The entities with MapLocation won't move often if at all once in place. Does anyone have good experience as to what the best practice is for this case?
     
  2. brunocoimbra

    brunocoimbra

    Joined:
    Sep 2, 2015
    Posts:
    679
  3. DreamingImLatios

    DreamingImLatios

    Joined:
    Jun 3, 2017
    Posts:
    4,222
    If your map is immutable, a packed array of Entities and a NativeHashMap<int2, int2> is pretty optimal. Otherwise there's NativeMultiHashMap, NativeHashMap of UnsafeList, and NativeHashMap<int2, Entity> where the Entity is an entity with a dynamic buffer holding more entities.
     
  4. Enoch

    Enoch

    Joined:
    Mar 19, 2013
    Posts:
    198
    Fantastic, these are great solutions. I didn't even know NativeMultiHashMap existed, thanks for that. The idea of spawning another entity with a buffer to act a list is one that should have occurred to me. Great info, thanks again.