Search code examples
javaarraysminecraftbukkit

How do I perform an action only on the even something is removed from an array list?


Here is an example of what I'm working with...

    Player p = (Player) sender;
        ArrayList<Player> nofalldmg = new ArrayList<Player>();
    
        
        if (p.hasPermission("custome.fly")) {
            if (p.isFlying()) {
                p.setAllowFlight(false);
                p.setFlying(false);
                nofalldmg.add(p);
                Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
                    public void run() {
                        nofalldmg.remove(p);
                    }
                    }, 60);

So as you can see I have two lines of code 1 "nofalldmg.add(p);" that adds the player to an array list, and 2 "nofalldmg.remove(p);" that removes the player from the array list

When they are added to the array list their fall damage is canceled, what I want to know is once they are removed from that array list how do I re enable their fall damage?


Solution

  • This is the full class that can help you (without import, with comment to explain how it works) :

    private final ArrayList<Player> nofalldmg = new ArrayList<Player>(); // declare list
    
    @EventHandler
    public void onDamageDisabler(EntityDamageEvent e) { // method to disable fall damage
       if (e.getCause() == EntityDamageEvent.DamageCause.FALL) { // only if it's fall
          if(e.getEntity() instanceof Player && nofalldmg.contains((Player) e.getEntity()) { // only if it's in list
             e.setCancelled(true); // cancel
          }
       }
    }
    
    
    public void yourMethod(CommandSender sender) {
       Player p = (Player) sender;
       if (p.hasPermission("custome.fly")) { // your conditions
           if (p.isFlying()) {
              p.setAllowFlight(false);
              p.setFlying(false);
              nofalldmg.add(p); // here we add it to the list
              Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, () -> {
                 nofalldmg.remove(p);
                 // here you can resetting everything that you want
              }, 60); // no we remove it, so can take damage
           }
       }
    }