-
Notifications
You must be signed in to change notification settings - Fork 46
Registering and using a component
Pyrofab edited this page May 26, 2020
·
15 revisions
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 register your component type, using ComponentRegistry.registerIfAbsent;
the resulting ComponentType instance is used as a key for component providers.
public static final ComponentType<IntComponent> MAGIK =
ComponentRegistry.INSTANCE.registerIfAbsent(new Identifier("mymod:magik"), IntComponent.class);
public static void useMagik(ComponentProvider provider) {
// Retrieve a provided component
int magik = MAGIK.get(provider).getValue();
// Or, if the provider is not guaranteed to provide that component:
int magik = MAGIK.maybeGet(provider).map(IntComponent::getValue).orElse(0);
// ...
}Note: a component class can be reused for several component types