Structs and NativeContainer

Looking for some advice on best practice with utility classes, struct systems, and NativeContainer/Array/etc. One of my initialization systems creates a NativeHashMap<EntityA, EntityB> to help with repetitive prefab creation. I want to wrap this in a utility class to add some encapsulation and better ergonomics, but that makes it a reference type which makes any job working with it incompatible with Burst. Is best practice here to make it a struct like:

struct PrefabEntityMap {
  private NativeHashMap<Entity, Entity> container;
  ...
}

Since the NativeContainer is ultimately a pointer, passing around a struct (even without ref) will still reference the same unmanaged memory, right? I assume this also applies to NativeContainer fields on the upcoming struct systems?

I do this all the time. It works for all Native* types but breaks for all Unsafe* types.
Burst sometimes has a little bit of trouble understanding the aliasing behavior of these types, so if you know that an instance of the internal container will always be unique in any given job, you can add the [NoAlias] attribute to it.

1 Like

If you’re worried about disposal, just make sure that the wrapped class is given an Allocator to construct the container. Then, PrefabEntityMap can inherit IDisposable, and you can dispose the container in the Dispose method.

1 Like