Code Patterns

Copy-paste examples for common plugin tasks. Commands, events, ECS, GUI, and more.

← Back to Patterns
ecs

Component Iteration

Efficiently iterate over all entities with a specific component using forEachChunk for cache-friendly access.

Example Code

java
// Iterate all entities with PositionComponent
store.forEachChunk(positionType, (archetypeChunk, commandBuffer) -> {
    for (int i = 0; i < archetypeChunk.size(); i++) {
        // Get component directly from chunk (faster than store.getComponent)
        PositionComponent position = archetypeChunk.getComponent(i, positionType);

        // Get entity reference if needed
        Ref<EntityStore> ref = archetypeChunk.getReferenceTo(i);

        // Use commandBuffer for modifications (thread-safe)
        commandBuffer.addComponent(ref, velocityType, new VelocityComponent(0, -1, 0));
    }
});