Solved How do I make a custom event I can cancel?

Discussion in 'Plugin Development' started by Javed, Aug 3, 2015.

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

    Javed

    I'm trying to make a guns plugin, and I think it would be great if I could use custom events to make it compatible with other plugins. For example, making a capture the flag plugin and using the custom events to cancel shots that would otherwise damage teammates.

    I made a custom event and implemented Cancellable. I was able to create a listener which also works fine. The problem is that when I cancel the gun fire event, it still fires. Here is my event class.

    Code:
    public class GunFireEvent extends Event implements Cancellable {
        boolean cancelled = false;
        Gun gun;
        Wielder wielder;
       
        public GunFireEvent(Gun gun, Wielder wielder) {
            this.gun = gun;
            this.wielder = wielder;
           
            if(!cancelled) {
                gun.fire();
            }
        }
        public Gun getGun() {
            return gun;
        }
        public Wielder getWielder() {
            return wielder;
        }
       
        private static final HandlerList handlers = new HandlerList();
       
        public HandlerList getHandlers() {
            return handlers;
        }
        
        public static HandlerList getHandlerList() {
            return handlers;
        }
    
        @Override
        public boolean isCancelled() {
            return false;
        }
    
        @Override
        public void setCancelled(boolean arg0) {
            cancelled = arg0;
        }
    }
    How to I make setCancelled(true) prevent the firing of the gun?
     
  2. Offline

    schwabfl

    remove this part from the contructor
    Code:
    if(!cancelled) {
        gun.fire();
    }
    
    and then use this code whenever someone tries to shoot the gun, this will create an instance even and pass it to the pluginmanager to call the event, and shoot the gun if the event was not cancelled.
    Code:
    GunFireEvent e = new GunFireEvent(gun, wielder)
    Bukkit.getPluginManager().callEvent(e);
    if (!e.isCancelled()) {
        gun.fire();
    }
    
    You can then listen to te event how you would listen to any other event and cancel it when needed
     
  3. Offline

    Javed

    Thanks!
     
    Last edited: Aug 4, 2015
Thread Status:
Not open for further replies.

Share This Page