Search code examples
javaminecraftbukkit

Removing items from a Bukkit Inventory


I have a ItemStack, and I am trying to remove it from a player. I tried this successfully before, but now; I have no luck. I tried:

player.remove(new ItemStack(Material.COAL, 2));

And I have also tried to do this:

ItemStack itemStack = new ItemStack(Material.COAL);
player.remove(itemStack);

Solution

  • I found the solution and this static method does it wonderfully.

    public static void removeInventoryItems(PlayerInventory inv, Material type, int amount) {
        for (ItemStack is : inv.getContents()) {
            if (is != null && is.getType() == type) {
                int newamount = is.getAmount() - amount;
                if (newamount > 0) {
                    is.setAmount(newamount);
                    break;
                } else {
                    inv.remove(is);
                    amount = -newamount;
                    if (amount == 0) break;
                }
            }
        }
    }