Search code examples
javaminecraftbukkit

Spigot Unregister event with a command


I made a Plugin that registers an event, I want to make a command that unregisters it, how should I do it, I already searched for 2 h and I found nothing. I want to make /Pvpeventon to start the event and /Pvpeventoff to turn it off that is the code I already made: package me.leopa.R1.FFA;

import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;

import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.plugin.java.JavaPlugin;




public class MainFFA extends JavaPlugin implements Listener{
@Override
public void onEnable() {
    System.out.println("[INFO Leopa] Start");
    super.onEnable();
}

@Override
public void onDisable() {
System.out.println("[INFO Leopa] Stop");
super.onDisable();
}

@Override
public boolean onCommand(CommandSender sender, Command command, String    label, String[] args) {

    if(command.getName().equalsIgnoreCase("PVPEVENTon")) {
        getServer().getPluginManager().registerEvents(this, this);
    }

    if(command.getName().equalsIgnoreCase("PVPEVENToff")) {
        getServer().getPluginManager().
    }
    return super.onCommand(sender, command, label, args);


    }
@EventHandler
public void onDeathPVPEVENT(PlayerDeathEvent pvpevent) {
    Player p = pvpevent.getEntity();
    p.sendMessage("HI");
}





}`

Solution

  • Instead of unregister the event you should simplify it and add a boolean as variable which turns into false when the pvp should be disabled and to true if pvp is allowed:

    //Some Listener class
    ...
    private YourPlugin plugin; //example
    ...
    @EventHandler
    public void playerDeath(PlayerDeathEvent event) {
        if(plugin.isEventMode()) {  //TODO when event mode is on }
    }
    

    Plugin class

    ...
    public class YourPlugin extends JavaPlugin {
        ...
        private boolean eventMode; //false per default
        ...
    
        public boolean toggleEventMode() {
            eventMode = !eventMode; //negation so if it is true it will be turned into false if it is false it will be turned to true
            return eventMode;
        }
        public boolean isEventMode() {
            return eventMode;
        }
    }
    

    Command toggle event mode:

    //is declared somewhere
    boolean eventMode = plugin.toggleEventMode();
    //true if eventMode is on false if not.
    

    Note you can also use a setEventMode method.

    You also can use the unregisterAll method to unregister all events in a Listener or a Plugin:

    HandlerList.unregisterAll(this); //takes a listener or a plugin. In your case you got all stuff in one class it should still work.
    

    Check these methods: