Grabbing all of one specified item in a players inventory

Discussion in 'Spigot Plugin Development' started by PCPSells, Mar 10, 2019.

  1. I'd like to start this off with the fact that I'm not asking to be spoon fed the code but I'm confused.

    What I want to happen in simple terms:
    When I shift + click and item it removes all of that item type and I have the int of exactly how many were removed to add that to a custom balance for the player.

    My understanding of the coding method:
    Grab the players inventory, create an ItemStack not including an amount in the new ItemStack and if the players inventory contains that item then.. no clue exactly on how to get the exact amount of them, remove a certain amount without messing up amounts due to numerous stacks etc.

    Any help would be seriously appreciated. Thank you!
     
  2. Are you trying to Shift+Click delete that entire stack amount, or every single item in your inventory that is that type?
     
  3. Every single item in the inventory that is that exact item.
    The exact example I have is this:

    My players want a few custom currencies that have items in the server to usage as trading the currency.
    Like eTokens or something I have called Dust.
    Either way, when a player has an inventory full of eTokens or Dust and they shift + click one of that item it removes all of that exact ItemStack (Glowstone Dust named '&7Dust (Right Click)') / (Magma Cream named '&6Enchantment Token &7(Right Click)')

    I'll use Dust for this example but yes, shift + click any amount of dust in your hand it removes every single one of them from the players inventory and then I'm able to make an int with the amount that was removed to deposit that into their virtual balance.
    Thanks again!
     
  4. There are probably plenty of different ways, but this is a quick way I'd do it.

    Code (Text):
            Material im = event.getCurrentItem().getType();

            int count = 0;

            for (ItemStack content : event.getClickedInventory().getContents()) {
                if (content.getType() == im){
                    count += content.getAmount();
                }
            }
     
  5. Pseudo code:
    Code (Text):
    define a local variable sum
    save the clicked item in a variable
    loop through the inventory of player:
        use ItemStack#isSimilar to compare the current item of the loop to the clicked item:
            if the item is similar then get the items amount and add it to the sum variable
            remove the item from the inventory
     
     
  6. You'd rather remove the item from the inventory after the loop is done as this would cause issues. Such as only getting the sum of only the first itemstack found in the loop.
     
  7. You could also use the all method of the Inventory to find all items and then sum them.