Solved Add Item Always Returns Filled HashMap

Discussion in 'Plugin Development' started by Smeary_Subset, Jan 5, 2023.

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

    Smeary_Subset

    In one of my minigames, whenever a player breaks a block, the drops are supposed to go directly into their inventory instead of being dropped. If the items can't fit, they are dropped instead. However, what actually happens is, even when the inventory is not full, both the item is dropped and a duplicate is put into the player's inventory.

    I use the Inventory#addItem method, which is supposed to return a HashMap only of itemstacks that didn't fit in the inventory. The Paper API states:

    The returned HashMap contains what it couldn't store, where the key is the index of the parameter, and the value is the ItemStack at that index of the varargs parameter. If all items are stored, it will return an empty HashMap.

    However, it always returns all items that were dropped. Here's my code:

    Code:
        @EventHandler
        private void onBlockDropItem(BlockDropItemEvent event) {
            Player player = event.getPlayer();
            if(player == null || !isInGame(player)) return;
            List<Item> items = event.getItems();
            addToInv(items, player);
        }
    
        private void addToInv(List<Item> items, Player player) {
            PlayerInventory inv = player.getInventory();
            Location playerLoc = player.getLocation();
            World world = playerLoc.getWorld();
            HashMap<Integer, ItemStack> itemsThatDidntFit;
            for(Item item : items) {
                itemsThatDidntFit = inv.addItem(item.getItemStack());
                for(ItemStack extraItem : itemsThatDidntFit.values())
                    world.dropItem(playerLoc, extraItem);
            }
        }
     
  2. Offline

    Zxoir

    I think you forgot to cancel the event
     
    Strahan likes this.
  3. Offline

    Strahan

    What he said. Also, what is the point of making the items variable? Just do
    Code:
    addToInv(event.getItems(), player);
    Also, BlockDropItemEvent#getPlayer() cannot be null just FYI.
     
    Zxoir likes this.
  4. Offline

    Smeary_Subset

    Yup, you both are correct. I made the changes and it works.
     
Thread Status:
Not open for further replies.

Share This Page