Solved Removing an Enchantment from an enchanted book on PrepareAnvilEvent

Discussion in 'Spigot Plugin Development' started by stelioshah, Jun 12, 2021.

  1. I have created a plugin which allows to anvil overleveled enchanted books and items. It works fine for items and item + book combinations but it breaks when combining 2 books. To add the overleveled enchantments, I check if there are any overleveled enchantments withing the items and then I use the:

    event.getResult().addUnsafeEnchantment(enchantment, value);

    If I have an unbreaking III pickaxe and combine it with an unbreaking IV one I will now always get an unbreaking IV pickaxe.

    If the items were 2 books though, I would get an unbreaking III, unbreaking IV book. This has something to do with the keys. For the 2 books I am using:

    Code (Text):
    for(Map.Entry<Enchantment, Integer> ench: ((EnchantmentStorageMeta)theAnvil.getInventory().getContents()[1].getItemMeta()).getStoredEnchants().entrySet()) {
                   
                    if(ench.getValue() > ench.getKey().getMaxLevel()) {
                       
                        slot1Ench.put(ench.getKey(), ench.getValue());
                    }

                }
                for(Map.Entry<Enchantment, Integer> ench: ((EnchantmentStorageMeta)theAnvil.getInventory().getContents()[0].getItemMeta()).getStoredEnchants().entrySet()) {
                   
                    if(slot1Ench.containsKey(ench.getKey())) {

                        theAnvil.getResult().addUnsafeEnchantment(ench.getKey(), slot1Ench.get(ench.getKey()));
                    }
                   
                }
    slot1Ench is a Map that keeps the overleveled Enchantments of theAnvil's slot1 (I am only checking if there are overleveled enchantments on slot1 if they are on slot0 they are automatically "anvilable".

    upload_2021-6-12_16-34-26.png

    upload_2021-6-12_16-34-6.png
     

    Attached Files:

  2. EDIT: Fixed this, I had to change the ItemMeta in order for it to work:
    Code (Text):
    if(slot1Ench.containsKey(ench.getKey())) {

                        EnchantmentStorageMeta overleveldMeta = ((EnchantmentStorageMeta)theAnvil.getResult().getItemMeta());
                       
                        overleveldMeta.addStoredEnchant(ench.getKey(), slot1Ench.get(ench.getKey()), true);
                       
                        theAnvil.getResult().setItemMeta(overleveldMeta);
                       
                    }