Search Unity

NativeHashMap set value

Discussion in 'Entity Component System' started by e199, Dec 2, 2018.

  1. e199

    e199

    Joined:
    Mar 24, 2015
    Posts:
    101
    There is no method to update value for a specific key in NativeHashMap.

    In NativeMultiHashMap - there is one. But I know I will store only one value for each key in it and that collection has TryGetFirstValue which requires and makes things overly complex.

    Maybe I overlooked something?
     
  2. tertle

    tertle

    Joined:
    Jan 25, 2011
    Posts:
    3,761
    If you want to replace, just call remove beforehand.

    Code (CSharp):
    1. n.Remove(key);
    2. n.TryAdd(key, value);
    Ideally your code should be parallel but this only works in IJob so you usually fill NativeHashMaps using the Concurrent version which can't read which is required to replace.

    Ideally you should refactor your code to avoid the need to replace so you can parallelize it.
     
    Last edited: Dec 2, 2018
  3. e199

    e199

    Joined:
    Mar 24, 2015
    Posts:
    101
    Yeah, I did it like that, but it felt uncomfortable to look at :D
     
  4. tertle

    tertle

    Joined:
    Jan 25, 2011
    Posts:
    3,761
    Again, I feel like there is probably a better way to do what you want to do, but you can just use an extension method.

    Code (CSharp):
    1.         public static void AddOrReplace<TK, TV>(this NativeHashMap<TK, TV> hashMap, TK key, TV value)
    2.             where TK : struct, IEquatable<TK>
    3.             where TV : struct
    4.         {
    5.             hashMap.Remove(key);
    6.             hashMap.TryAdd(key, value);
    7.         }
    8.  
    hashMap.AddOrReplace(1, 2);
     
    SirDorius9 and davenirline like this.