1.17.x how to add enchantments to the lore

Discussion in 'Spigot Plugin Development' started by mason-walker, Jun 28, 2021.

  1. I want my lore to show up before my enchantments, so how can I get the enchantments, and their levels, and add it to the lore, then I can apply hide enchants.
     
  2. It essentially boils down to replacing old lore with new lore:

    Code (Java):

    public void updateEnchantment(ItemStack i, String enchantmentName, String replaceWith){
        if (i == null) return;
        ItemMeta meta = i.getItemMeta();
        assert meta != null;

        List<String> lore = meta.getLore();
        if (lore == null) lore = new ArrayList<>();
        int matchLoreIndex = -1;
        for (String l : lore){
            //Checking all lines of lore for matches with enchantmentName
            if (l.contains(" ")){
                String[] splitString = l.split(" ");
                if (splitString.length >= 2){
                    String matchString = String.join(" ", Arrays.copyOfRange(splitString, 0, splitString.length - 1));
                    // If the enchantmentName largely matches what is on the item (the enchantment name minus its strength) its index is noted
                    if (enchantmentName.equals(matchString)){
                        matchLoreIndex = lore.indexOf(l);
                        break;
                    }
                }
            }
        }

        if (matchLoreIndex != -1) {
            lore.set(matchLoreIndex, Utils.chat(replaceWith)); //Utils.chat() is a method to convert color codes to ChatColors
        } else {
            lore.remove(matchLoreIndex);
        }
        meta.setLore(lore);
        i.setItemMeta(meta);
    }
     
    for enchantmentName put in whatever the name of your enchantment is, like maybe "&7Fire Aspect". So if you have some lore on your item that says "&7Fire Aspect II", it will separate the II from the rest and try to match "&7Fire Aspect" with "&7Fire Aspect", which is true, so it replaces "&7Fire Aspect" with whatever you put in replaceWith which could be "&7Fire Aspect III" for example. If "&7Fire Aspect" is not found in the lore, it is removed instead.