Access dynamic buffers in a chunk
To access all dynamic buffers in a chunk, use the ArchetypeChunk.GetBufferAccessor
method. This takes a BufferTypeHandle<T>
and returns a BufferAccessor<T>
. If you index the BufferAccessor<T>
, it returns the chunk's buffers of type T
:
The following code sample shows how to access every dynamic buffer of a type in a chunk.
[InternalBufferCapacity(16)]
public struct ExampleBufferComponent : IBufferElementData
{
public int Value;
}
public partial class ExampleSystem : SystemBase
{
protected override void OnUpdate()
{
var query = new EntityQueryBuilder(Allocator.Temp)
.WithAllRW<ExampleBufferComponent>()
.Build(EntityManager);
NativeArray<ArchetypeChunk> chunks = query.ToArchetypeChunkArray(Allocator.Temp);
for (int i = 0; i < chunks.Length; i++)
{
UpdateChunk(chunks[i]);
}
}
private void UpdateChunk(ArchetypeChunk chunk)
{
// Get a BufferTypeHandle representing dynamic buffer type ExampleBufferComponent from SystemBase.
BufferTypeHandle<ExampleBufferComponent> myElementHandle = GetBufferTypeHandle<ExampleBufferComponent>();
// Get a BufferAccessor from the chunk.
BufferAccessor<ExampleBufferComponent> buffers = chunk.GetBufferAccessor(ref myElementHandle);
// Iterate through all ExampleBufferComponent buffers of each entity in the chunk.
for (int i = 0, chunkEntityCount = chunk.Count; i < chunkEntityCount; i++)
{
DynamicBuffer<ExampleBufferComponent> buffer = buffers[i];
// Iterate through all elements of the buffer.
for (int j = 0; j < buffer.Length; j++)
{
// ...
}
}
}
}