Skip to content

Instantly share code, notes, and snippets.

@LlamaLad7
Last active October 24, 2022 15:52
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save LlamaLad7/0b553d5ae04e4eb44d3a1e8558be9151 to your computer and use it in GitHub Desktop.
Save LlamaLad7/0b553d5ae04e4eb44d3a1e8558be9151 to your computer and use it in GitHub Desktop.
Adding to enums safely with mixin
public class CustomAxolotlVariant {
static {
AxolotlEntity.Variant.values(); // Ensure class is loaded before the variant is accessed
}
public static AxolotlEntity.Variant PURPLE;
}
public class ExampleMod implements ModInitializer {
@Override
public void onInitialize() {
// All these operations now work as expected!
System.out.println(CustomAxolotlVariant.PURPLE);
System.out.println(CustomAxolotlVariant.PURPLE.getId());
System.out.println(CustomAxolotlVariant.PURPLE.getName());
System.out.println(Arrays.toString(AxolotlEntity.Variant.VARIANTS));
System.out.println(Arrays.toString(AxolotlEntity.Variant.values()));
System.out.println(AxolotlEntity.Variant.valueOf("PURPLE"));
}
}
@Mixin(AxolotlEntity.Variant.class)
public abstract class VariantMixin {
@SuppressWarnings("InvokerTarget")
@Invoker("<init>")
private static AxolotlEntity.Variant newVariant(String internalName, int internalId, int id, String name, boolean natural) {
throw new AssertionError();
}
@SuppressWarnings("ShadowTarget")
@Shadow
private static @Final
@Mutable
AxolotlEntity.Variant[] field_28350;
@SuppressWarnings("UnresolvedMixinReference")
@Inject(method = "<clinit>", at = @At(value = "FIELD", opcode = Opcodes.PUTSTATIC, target = "Lnet/minecraft/entity/passive/AxolotlEntity$Variant;field_28350:[Lnet/minecraft/entity/passive/AxolotlEntity$Variant;", shift = At.Shift.AFTER))
private static void addCustomVariant(CallbackInfo ci) {
var variants = new ArrayList<>(Arrays.asList(field_28350));
var last = variants.get(variants.size() - 1);
// This means our code will still work if other mods or Mojang add more variants!
var purple = newVariant("PURPLE", last.ordinal() + 1, last.getId() + 1, "purple", true);
CustomAxolotlVariant.PURPLE = purple;
variants.add(purple);
field_28350 = variants.toArray(new AxolotlEntity.Variant[0]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment