get free Inventory slots (without armor)

Discussion in 'Plugin Development' started by Macklan, Sep 1, 2022.

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

    Macklan

    I have found the following code, that checks for the amount of free slots.
    But it does so by taking 5 slots into account for the armor.

    What I would need is a way to check the pure inventory (all slots (4x9 = 45 slots), but without armor) to check if I can drop the player a new item.

    Code:
    public int getFreeSlots(Player player) {
        int freeslots = 0;
        for (ItemStack it : player.getInventory().getContents()) {
            if (it == null || it.getType() == Material.AIR) {
                freeslots++;
            }
        }
        freeslots = freeslots - 5; // subtract shield and armor
    
        return freeslots;
    }
     
  2. Offline

    KarimAKL

    @Macklan You can use a standard for loop to iterate the slots in the inventory.
    Here's some pseudo-code to serve as an example.
    Code:Java
    1. int emptySlots = 0
    2. for (int slot = 0; slot < inventory.size):
    3. if inventory.getItem(slot) == null:
    4. emptySlots += 1
    5. return emptySlots
     
Thread Status:
Not open for further replies.

Share This Page