Storing arrays in NativeHashMap

How do I go about doing that given that TValue must be a non-nullable type. Googling the problem tells me that I have to do the following:

public NativeHashMap<int3, NativeArray<int>> foo = new NativeHashMap<int3, NativeArray<int>>();

However either that no longer works or it’s never worked.

For solutions two things are useful/important:

  • All arrays are the same size.
  • The order of the contents is important.

What error are you getting?

The type 'NativeArray<int>' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'TValue' in the generic type or method 'NativeHashMap< TKey, TValue>'

Replace the inner collection with its “unsafe” variant.

Also, save yourself from pointlessly repetitive code with the var keyword or the intelligent new():

This is what you need:

public NativeHashMap<int3, UnsafeList<int>> foo = new NativeHashMap<int3, UnsafeList<int>>();

This is how you should be writing it:

public NativeHashMap<int3, UnsafeList<int>> foo = new();

Or where it’s not a field, it would be this:

var foo = new NativeHashMap<int3, UnsafeList<int>>();
1 Like

Worth noting the error message encountered here only applies to 2021 LTS or older. In 2022 LTS and newer, this would be valid.

Worth noting the error message encountered here only applies to 2021 LTS or older. In 2022 LTS and newer, this would be valid.

This is why i asked, as i couldnt replicate the error. But from 2022 onward, even though you can compile, you will still get an error if you try to use the hashmap in a Job. “Nested native containers are illegal in jobs.

However using UnsafeList as mentioned by @CodeSmile is “legal” and works. Im guessing however that at the cost of “safe” write&read error handling, hence the “unsafe” prefix

Might be worth looking into NativeParallelMultiHashMap. I use it for a grid system where the key is a position hash and the value is everything in that grid cell. It should fullfill your requirements of size and order requirements since those would just be dependent on the amount and order when you put things in the bucket.

1 Like