Solved Using Damageable to set the durability of a tool

Discussion in 'Spigot Plugin Development' started by Cynadyde, Mar 22, 2020.

  1. This might be a derpy question, but how do I set durability on an item stack using Damageable?

    My original thought was to do:
    Code (Text):
    ItemStack tool;  // get the item
    tool.setDurability((short) 5);
    but, this method is deprecated in the API, and it suggests getting/setting the item's meta and using Damageable. I attempted to do:
    Code (Text):
    import org.bukkit.inventory.meta.Damageable;
    // ...
    ItemStack tool;  // get the item
    if (tool.getItemMeta() instanceof Damageable) {
        Damageable meta = ((Damageable) tool.getItemMeta());
        meta.setDamage(5);
        tool.setItemMeta(meta);
    }
    but, Damageable doesn't extend ItemMeta, meaning tool.setItemMeta(meta) would be a compile error. Is this a Spigot bug or am I dumb? Is Damageable meant to extend ItemMeta?

    What am I missing?
     
  2. Ignore that ItemStack#setDurability is deprecated.
    ItemStack#setDurability is getting Damagable by item meta, and setting damage.
     
  3. The implementation of itemmeta also implements Damageable. Just save the Itemmeta first, do your stuff with casted version Damageable and after that set the uncasted itemmeta back to the stack.
     
  4. If it's deprectated it's most likely to assume it has a reason
    a method used
    Code (Text):
    private void repairItems(Player p) {
            Inventory pInv = p.getInventory();
            for(ItemStack item:pInv) {
                if(!item.hasItemMeta()) {
                    return;
                }
                    ItemMeta im = item.getItemMeta();
                    if(im instanceof Damageable) {
                        Damageable dmg = (Damageable) im;
                        if(dmg.hasDamage()) {
                            dmg.setDamage(dmg.getDamage()-1);
                        }
                        item.setItemMeta(im);
                    }
            }
        }
    This repairs each item by 1 durability

    The -1 to increase the durability while +1 to decrease it