← Back to Roadmap

Custom Components

30 min

Create your own ECS components to store custom data.

Custom Components

Components store data on entities. Create your own for custom features.

Defining a Component

java
public class Bounty extends Component {
    private static final ComponentType<Bounty> TYPE =
        ComponentType.create(Bounty.class, Bounty::new);

public static ComponentType<Bounty> getComponentType() { return TYPE; }

private int amount; private String setBy;

public Bounty() { this.amount = 0; this.setBy = null; }

public int getAmount() { return amount; } public void setAmount(int amount) { this.amount = amount; }

public String getSetBy() { return setBy; } public void setSetBy(String setBy) { this.setBy = setBy; } }

Using Components

java
// Add component to entity
Ref<EntityStore> ref = player.getEntityRef();
ref.add(Bounty.getComponentType(), new Bounty());

// Get component from entity Holder<EntityStore> holder = ref.toHolder(); Bounty bounty = holder.getComponent(Bounty.getComponentType());

// Modify component bounty.setAmount(100); bounty.setSetBy("BountyHunter");

// Check if entity has component if (holder.hasComponent(Bounty.getComponentType())) { // ... }

// Remove component ref.remove(Bounty.getComponentType());

Component Best Practices

  • Keep components small - one responsibility per component
  • No logic in components - components are data only
  • Use primitive types - for better serialization
  • Provide getComponentType() - static accessor for the type