Code Patterns

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

← Back to Patterns
ecs

Custom Component Definition

Define custom ECS components with proper clone support and optional serialization.

Example Code

java
public class HealthComponent implements Component<EntityStore> {
    private float maxHealth;
    private float currentHealth;

    public HealthComponent(float maxHealth) {
        this.maxHealth = maxHealth;
        this.currentHealth = maxHealth;
    }

    // Copy constructor for cloning
    public HealthComponent(HealthComponent other) {
        this.maxHealth = other.maxHealth;
        this.currentHealth = other.currentHealth;
    }

    // Required for entity duplication
    @Override
    public HealthComponent clone() {
        return new HealthComponent(this);
    }

    // Optional: exclude transient data from saves
    @Override
    public HealthComponent cloneSerializable() {
        return clone();
    }

    // Getters and setters
    public float getMaxHealth() { return maxHealth; }
    public float getCurrentHealth() { return currentHealth; }
    public void setCurrentHealth(float health) {
        this.currentHealth = Math.min(health, maxHealth);
    }
    public void damage(float amount) {
        this.currentHealth = Math.max(0, currentHealth - amount);
    }
    public boolean isDead() { return currentHealth <= 0; }
}

// Register in plugin setup:
getEntityStoreRegistry().registerComponent(
    HealthComponent.class,
    "Health",
    HealthComponent.CODEC  // Optional: for persistence
);