Solved Prevent blocks from being exploded in EntityExplodeEvent

Discussion in 'Spigot Plugin Development' started by Justin393, Nov 6, 2020.

  1. I'm currently creating a land claim plugin, and I have gotten to the point where I am accounting for grief. What I am trying to do is make it so that an explosion that takes place in an unclaimed chunk will not affect a neighboring claimed chunk, but I cannot seem to get it working.

    In EntityExplodeEvent you can get a blocklist which contains all of the blocks affected, but my best guess is the explosion is happening too fast for them to be removed.
    I have attached a picture to help understand what I am looking for. The left chunk is unclaimed (and where the TNT was placed), and the right chunk is the claimed one.

    Here is the code I am using:
    Code (Java):
    @EventHandler(priority = EventPriority.HIGHEST)
        public void onExplode(EntityExplodeEvent event) {
            List<Block> list = new ArrayList<>();
            for (Block block : event.blockList()) {
                if (ClaimManager.getInstance().isChunkClaimed(block.getChunk())) {
                    Bukkit.broadcastMessage("Block is protected, adding to list!");
                    list.add(block);
                }
            }
            for (int i = 0; i < list.size(); i++) {
                Bukkit.broadcastMessage("Removing block " + i + " from explosion!");
                event.blockList().remove(i);
            }
            list.clear();

        }

    I tried doing:
    for (Block block: event.blockList() {
    if (chunkBlockIsInIsClaimed() //Pseudo code
    event.blockList().remove()
    }

    But Java throws a ConcurrentModificationException since I'm deleting from the List while Iterating through it, that is why I'm adding to a Seperate List the protected blocks and removing them later.

    Any ideas on why this way is not working?
     

    Attached Files:

  2. You're not removing blocks you stored in the list. Instead, you remove the first block, then the second of what remains, then the third of what remains and so on. That's why it looks as if some random blocks were removed.

    Here are possible 2 solutions:
    1. Iterate through the list back to front, that way you can remove items from the list inside the loop
    2. event.blockList().removeAll(list)
     
    #2 Ivan1pl, Nov 6, 2020
    Last edited: Nov 7, 2020
    • Winner Winner x 1
  3. Figured it was something stupid lol.

    For future Googlers:

    needs to be event.blockList().remove(list.get(i));
    instead of event.blockList().remove(i);