Remove one of one items kind from inventory

Discussion in 'Plugin Development' started by DS_STORE, Feb 6, 2016.

Thread Status:
Not open for further replies.
  1. Offline

    DS_STORE

    I want kind of an ammo system where a custom Material.GOLD_NUGGET is the ammo.
    At the moment im checking if event.getPlayer.getInventory.containsAtLeast(CustomItems.SNIPER_AMMO, 1) before fireing... The problem is the removal of the item.
    At the moment im using: (to lazy to convert my scala to 100% java code, if something is unclear ask)
    Code:
    ItemStack isRemoveAmmo = CustomItems.SNIPER_AMMO.clone()
    isRemoveAmmo.setAmount(-1)
    event.getPlayer.getInventory.addItem(isRemoveAmmo)
    which is a bit buggy when a player has a whole stack. Then it adds a new stack with amount set to -1.
    Is there a elegant way to do this?
     
  2. Offline

    WolfMage1

  3. Offline

    GetSomePanda

    Wouldn't you just use this ?

    Code:
    player.getInventory().removeItem(isRemoveAmmo);
    player.updateInventory();
     
    Last edited: Feb 7, 2016
  4. Offline

    DS_STORE

    because Player#updateInventory() "should not be relied on"
     
  5. Offline

    timtower Administrator Administrator Moderator

    @DS_STORE Bukkit.getPlayer(string) is also deprecated, but it is the only good way to get a player by name.
    Just use the method, it is the only one out there.
     
  6. That method doesn't exist.

    Of course it is adding a new ItemStack with -1, you never removed the old ItemStack, and since the player have a full stack (64) the method .addItem() can't add it to that ItemStack, that's why it will be added as a different ItemStack, and since you set it's amount to -1 it will be displayed like that.

    I would make it like, a method with the amount of items to remove, then loop through player's inventory, checking if the item is the one that you want, if itemStack.getSize() - itemsToRemove > 0, then set the amount of the ItemStack to it, if not then remove to ItemToRemove the size of that itemStack and remove that ItemStack from the Inventory, and continue...

    I hope you understand me, my english is not very good.
     
Thread Status:
Not open for further replies.

Share This Page