-
-
Save LlamaLad7/0b553d5ae04e4eb44d3a1e8558be9151 to your computer and use it in GitHub Desktop.
Adding to enums safely with mixin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class CustomAxolotlVariant { | |
static { | |
AxolotlEntity.Variant.values(); // Ensure class is loaded before the variant is accessed | |
} | |
public static AxolotlEntity.Variant PURPLE; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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")); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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