#Apply custom enchantment to item when crafted (>24w18a)

1 messages · Page 1 of 1 (latest)

wintry glen
#

i'd like to have an item i created come with the custom enchantment already applied to it after being crafted.

the discussion in this thread (https://discord.com/channels/507304429255393322/1239062451681624075) allowed me to have access to the RegistryEntry of my custom enchantment, so i've tried overriding the item's onCraft method like this;

    @Override
    public void onCraft(ItemStack stack, World world) {
        super.onCraft(stack, world);
        stack.addEnchantment(enchantmentRegistryEntry, 1);
    }

when crafting the item, i get the attached error. this seems to be related to networking or client/server desync in some way, but i can't make sense of it myself. i've tried it with vanilla enchantments too, so i don't think its related to the custom enchantment itself. how would i go about fixing this? thank you in advance 🦭

wintry glen
#

trying to use the EnchantmentHelper class like this also causes the same issue

    @Override
    public void onCraft(ItemStack stack, World world) {
        ItemEnchantmentsComponent.Builder ecb = new ItemEnchantmentsComponent.Builder(stack.getEnchantments());
        ecb.add(EnchantmentRegistryLookup.getRegistryEntry(world, RegistryKey.of(RegistryKeys.ENCHANTMENT, enchantment)), 1);
        EnchantmentHelper.set(stack, ecb.build());
        super.onCraft(stack, world);
    }