[SOLVED] Check Player Permission During ChangeBlockEvent

Currently I am trying to check if:

  1. A player is the cause of a ChangeBlockEvent.Break
  2. If said player has xyz permission

Right now I have:

public class EventBlockBreak {
	
	@Listener
	public void onBlockBreakByEntity(ChangeBlockEvent.Break event){

		if (event.getCause().root() instanceof Player){
			if (event.getTransactions().get(0).getOriginal().getLocation().get().getBlockX() >= -1342 && event.getTransactions().get(0).getOriginal().getLocation().get().getBlockX() <= 1046 && event.getTransactions().get(0).getOriginal().getLocation().get().getBlockZ() >= -1254 && event.getTransactions().get(0).getOriginal().getLocation().get().getBlockY() <= 1198){
				if(event.getPlayer().hasPermission("Esinia.Server.Admin")){
					
				} else {
				event.setCancelled(true);
				}
			}
			
		} else {
			event.setCancelled(true);
		}
	}
}

The line in question that doesn’t work is:

if(event.getPlayer().hasPermission("Esinia.Server.Admin")){
1 Like

What do you mean ‘doesn’t work’? And ChangeBlockEvent.Break doesn’t have a method ‘getPlayer’.

What would be a proper way to check if a player has a permission during a blockbreak event which is caused by a player?

You already got your cause-root-object with event.getCause().root(), and checked with instanceof Player if it is a Player…

… So you can just cast the cause-root-object to a player:
Player player = (Player) event.getCause().root();

And there you go:

@Listener
public void onBlockBreakByEntity(ChangeBlockEvent.Break event){
	
	Object potentialPlayer = event.getCause().root();
	if (potentialPlayer instanceof Player){
		Player player = (Player) potentialPlayer;
		
		Location<World> loc = event.getTransactions().get(0).getOriginal().getLocation().get();
		if (loc.getBlockX() >= -1342 && loc.getBlockX() <= 1046 && loc.getBlockZ() >= -1254 && loc.getBlockY() <= 1198){
			if(player.hasPermission("Esinia.Server.Admin")){
				
			} else {
				event.setCancelled(true);
			}
		}
		
	} else {
		event.setCancelled(true);
	}
}
1 Like

That can be simplified even further with event filters

@Listener
public void onBlockBreakByPlayer(ChangeBlockEvent.Break event, @Root Player player) {
    Location<World> loc = event.getTransactions().get(0).getOriginal().getLocation().get();
    if (loc.getBlockX() >= -1342 && loc.getBlockX() <= 1046 && loc.getBlockZ() >= -1254 && loc.getBlockY() <= 1198){
        if(!player.hasPermission("Esinia.Server.Admin")){
            event.setCancelled(true);
        }
    }
}

Although then it can’t be cancelled if the root isn’t a player…

Thank you guys!

I just started developing my first plugin yesterday so this is all very new to me and I’m learning as I go.