Search code examples
pluginsminecraftspigot

Minecraft Spigot Remove Item From Inventory After Command (Sorry I Am Pretty New At This)


Picture Of My Code So Far

I'm stuck on how to remove an item from a player's inventory. I tried looking around but couldn't find anything I was looking for. So I decided to reach out and ask, this is my first time doing something like this.


Solution

  • Your inner static method removeItemFromInventory won't work there; you can't directly nest methods in Java. However, it's not necessary anyway.

    Looking at the Spigot documentation, there's a remove method on the entity's Inventory, so we could remove an item like so:

    player.getInventory().remove(new ItemStack(Material.DIAMOND, 1));
    

    However, as noted in the documentation:

    This will only match a slot if both the type and the amount of the stack match

    So this will only remove one diamond if the player has a slot containing only one diamond; it will not attempt to remove if they had two, for example.

    Therefore, we need to do some leg work:

    // Iterate over the player's inventory
    for (ItemStack itemStack : player.getInventory()) {
        // Check that the ItemStack isn't null (empty/air slots) or if it's not a slot containing diamonds
        if(itemStack == null || !itemStack.getType().equals(Material.DIAMOND)) {
            // if so, skip running further logic on this stack
            continue;
        }
        // Remove one from the amount, the ItemStack will be removed if it has 0 amount
        itemStack.setAmount(itemStack.getAmount() - 1);
        // Break out of the parent for loop to avoid removing more than we want
        break;
    }
    

    You could extract this logic into a method with a signature like reduceItemStackByAmount(Player player, Material material, int amount); however, you will need to add extra logic for when the amount is greater than a stack (64) and account for the stack size being smaller than the amount you're trying to remove. I'll leave this implementation up to you as a learning exercise.

    P.S. For future StackOverflow questions, take the tour and read How do I ask a good question? Also why you shouldn't post images of code.