-
Notifications
You must be signed in to change notification settings - Fork 46
Registering and using a component
To get started, you only need a class implementing the Component interface. It is good practice to make an interface for your component separate from the implementation, so that internals get properly encapsulated and so that the component itself can be used as an API by other mods.
Example:
interface IntComponent extends Component {
int getValue();
}
class RandomIntComponent implements IntComponent {
private int value = (int) (Math.random() * 20);
@Override public int getValue() { return this.value; }
@Override public void fromTag(CompoundTag tag) { this.value = tag.getInt("value"); }
@Override public CompoundTag toTag(CompoundTag tag) { tag.putInt("value", this.value); return tag; }
}All that is left is to actually use that component.
Components are provided by various objects through the ComponentProvider interface.
To interact with those, you need to obtain a ComponentType instance - a unique key made up of an identifier and of the component's type information. Such an instance can be retrieved in a few ways, all using the ComponentRegistry. Note that the same Component implementation can be reused between several ComponentTypes.
Most commonly, mods use ComponentRegistry#getOrRegister(Identifier, Class). This method must be called at least once to make the component usable in a game instance, but it can be called an arbitrary amount of times with no side-effects. If your mod uses another mod's component, you may not want to (or may not be able to) register it yourself - in which case you can use one of the other get methods.
// retrieving a type for my component or for a required dependency's
public static final ComponentType<IntComponent> MAGIK =
ComponentRegistry.INSTANCE.registerIfAbsent(new Identifier("mymod:magik"), IntComponent.class);
// retrieving a component type registered by an optional dependency
public static final Lazy<Optional<ComponentType<?>>> BLUE =
ComponentRegistry.INSTANCE.getLazyOptional(new Identifier("theirmod:blue"));