Skip to content

Instantly share code, notes, and snippets.

@niklaswimmer
Created December 10, 2021 14:38
Show Gist options
  • Save niklaswimmer/a17812bac9de4cf064baa789e9ccb96a to your computer and use it in GitHub Desktop.
Save niklaswimmer/a17812bac9de4cf064baa789e9ccb96a to your computer and use it in GitHub Desktop.
Getting Started with Capabilities: a practical example
public class MyCapability {
public static final Capability<MyCapabilityInterface> INSTANCE = CapabilityManager.get(new CapabilityToken<>() {});
public static void register(RegisterCapabilitiesEvent event) {
event.register(MyCapabilityInterface.class);
}
private MyCapability() {
}
}
public class MyCapabilityAttacher {
private static class MyCapabilityProvider implements ICapabilityProvider, INBTSerializable<CompoundTag> {
public static final ResourceLocation IDENTIFIER = new ResourceLocation("mod_id", "myCap");
private final MyCapabilityInterface backend = new MyCapabilityImplementation();
private final LazyOptional<MyCapabilityInterface> optionalData = LazyOptional.of(() -> backend);
@NotNull
@Override
public <T> LazyOptional<T> getCapability(@NotNull Capability<T> cap, @Nullable Direction side) {
return MyCapability.INSTANCE.orEmpty(cap, this.optionalData);
}
void invalidate() {
this.optionalData.invalidate();
}
@Override
public CompoundTag serializeNBT() {
return this.backend.serializeNBT();
}
@Override
public void deserializeNBT(CompoundTag nbt) {
this.backend.deserializeNBT(nbt);
}
}
public static void attach(final AttachCapabilitiesEvent<Entity> event) {
final MyCapabilityProvider provider = new MyCapabilityProvider();
event.addCapability(MyCapabilityProvider.IDENTIFIER, provider);
event.addListener(provider::invalidate);
}
private MyCapabilityAttacher() {
}
}
public class MyCapabilityImplementation implements MyCapabilityInterface {
private static final String NBT_KEY_DAMAGE_DEALT = "damageDealt";
private String myValue = "";
@Override
public String getValue() {
return this.myValue;
}
@Override
public void setMyValue(String myValue) {
this.myValue = myValue;
}
@Override
public CompoundTag serializeNBT() {
final CompoundTag tag = new CompoundTag();
tag.putString(NBT_KEY_DAMAGE_DEALT, this.myValue);
return tag;
}
@Override
public void deserializeNBT(CompoundTag nbt) {
this.myValue = nbt.getString(NBT_KEY_DAMAGE_DEALT);
}
}
public interface MyCapabilityInterface extends INBTSerializable<CompoundTag> {
String getValue();
void setMyValue(String myValue);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment