Search Unity

Help with basic NativeHashMap usage (add/update key/value and ContainsKey() )

Discussion in 'Entity Component System' started by sSaltyDog, Feb 4, 2019.

  1. sSaltyDog

    sSaltyDog

    Joined:
    Mar 4, 2017
    Posts:
    37
    Currently I'm using a managed dictionary in my project: System.Collections.Generic.Dictionary<float3, MyStruct[]>

    My assumption is that I should be using a NativeHashMap as a matter of best practice, as I am going to a pure ECS project (as far as that's possible with the current state of ECS. I'm really struggling to find NativeHashMap examples online, hence this thread.

    1. I've been testing NativeHashMap and I'm a little confused about how to use it. Firstly if I try to assign to it, I get an error:
    Code (CSharp):
    1. myNativeHashMap[key] = value
    2.  
    3. Property or indexer 'NativeHashMap<float3, NativeArray<MapSaveSystem.SaveData>>.this[float3]' cannot be assigned to -- it is read only [Assembly-CSharp]

    I'm guessing this is expected, but the only other way to assign that I can see to assign a value to a new key is TryAdd() which presumably (going by Dictionary.TryGetValue() ) won't perform well. Am I missing something here, or is the only way to assign to a NativeHashMap TryAdd()? I notice NativeHashMap.Concurrent mentioned here but I'm currently working in the main thread and this seems to be specifically for parallel operations.

    2. Since the values of my dictionary are collections, I would also like to do this:
    Code (CSharp):
    1. myNativeHashMap[key][index] = value
    But, from what I can see, this simply isn't possible.

    3. I am currently using ContainsKey() to check the existence of a key and not TryGetValue(). ContainsKey is more suited to my needs. NativeHashMap only has TryGetValue which would result in my using a superfluous variable for the out parameter (assuming I had the rest of my function working with NativeHashMap).

    - Does anyone have any examples of NativeHashMap I can refer to?
    - Regarding 1, 2 and 3 above - am I coming up against simple limits in functionality here or am I missing something?

    Thanks! :)
     
    kiaat and T-Zee like this.
  2. tertle

    tertle

    Joined:
    Jan 25, 2011
    Posts:
    3,759
    You can't assign collections inside native containers. However there is a NativeMultiHashMap for you to use
     
    sSaltyDog likes this.
  3. GilCat

    GilCat

    Joined:
    Sep 21, 2013
    Posts:
    676
    NativeMultiHashMap is definitely the way to go.
    You should watch this presentation about its usage in jobs, you can also find usage of it in the Boid Demo.
     
    sSaltyDog likes this.