Prevent destroying a not empty chest

Discussion in 'Plugin Development' started by Ahmet094, Sep 10, 2012.

Thread Status:
Not open for further replies.
  1. Why doesn't this work?
    This way I can't destroy any chest, doesn't matter if it's empty or not

    Code:
        @EventHandler
        public void preventDestroyingNotEmptyChest(BlockBreakEvent event) {
            Block block = event.getBlock();
            if (block.getType() == Material.CHEST) {
                Chest chest = (Chest) block.getState();
                if (chest.getInventory().getContents() != null) {
                    event.setCancelled(true);
                }
     
            }
        }
    And this way I'm able to destroy it, even if it's full..

    Code:
        @EventHandler
        public void preventDestroyingNotEmptyChest(BlockBreakEvent event) {
            Block block = event.getBlock();
            if (block.getType() == Material.CHEST) {
                Chest chest = (Chest) block.getState();
                if (chest.getInventory().getContents().length == 0) {
                    event.setCancelled(true);
                }
     
            }
        }
     
  2. Offline

    Seadragon91

    The chest.getInventory().getContents() has a fixed size that contains ItemStacks or null values.
    Idea:
    Go trough all items over a foreach loop and check if it's not null if that is true then cancel the event directly.
     
  3. Mhm okay..
    Could you please provide an example code?
     
  4. Offline

    MrFigg

    Code:
        @EventHandler
        public void preventDestroyingNotEmptyChest(BlockBreakEvent event) {
            Block block = event.getBlock();
            if(block.getType() == Material.CHEST) {
                Chest chest = (Chest) block.getState();
                boolean empty = true;
                for(ItemStack item : chest.getInventory().getContents()) {
                    if(item!=null&&item.getType()!=null&&!item.getType().equals(Material.AIR)) {
                        empty = false;
                        break;
                    }
                }
                if(!empty) {
                    event.setCancelled(true);
                }
            }
        }
     
    Ahmet094 likes this.
  5. Thanks for your help! :)
     
  6. Offline

    Seadragon91

    I do not see the need of a boolean value. If you find a item that is not null, why not cancel the event directly and make return; ?
     
  7. Offline

    MrFigg

    Very true. I did it so fast I didn't even think about it.
     
Thread Status:
Not open for further replies.

Share This Page