Custom Components
30 minCreate your own ECS components to store custom data.
Custom Components
Components store data on entities. Create your own for custom features.
Defining a Component
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
// 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());