Sharing Data in Unity ECS

One challenge I ran into early when developing in Unity ECS was how to share data between systems. There’s a million reasons you might want to do this. In my case, I wanted efficient read-only access to data stored against other entities so I can pre-cull faces on generated meshes. I struggled with how to make this happen.

Here’s a solution I was finally able to get going:

public readonly struct SurfaceChunkWrapper {
  private readonly NativeHashMap<int3, SurfaceChunkData> _chunkData);

  public SurfaceChunkWrapper(NativeHashMap<int3, SurfaceChunkData chunkData) {
    _chunkData = chunkData;
  }

  public bool TryGetChunkData(int3 pos, out SurfaceChunkData chunkData) => _chunkData.TryGetValue(pos, out chunkData);
}

public class SurfaceChunkDataSystem : SystemBase {
  private NativeHashMap<int3, SurfaceChunkData> _chunkIndex;
  public SurfaceChunkWrapper ChunkData => new SurfaceChunkWrapper(_chunkIndex);

  protected override void OnUpdate() {
    // Your code
  }
}

Using the above pattern, your other ECS Systems are able to easily gain read-only access to data you store in other systems.

Next
Next

Unity C# Job System and Coroutines