Search code examples
javaminecraftbukkit

Turn event on and off with /command /on or /command off


I want to make an PVPEventPlugin plugin and turn the events on and off , but I want to make /pvpevent on and /pvpevent off but I need to do this with args. This is my code:

@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {      
    if(command.getName().equalsIgnoreCase("PVPEVENTon") {
        if(sender instanceof Player) {
            getServer().getPluginManager().registerEvents(this, this);
            for (Player player : Bukkit.getOnlinePlayers()) {
                player.sendMessage(ChatColor.GREEN + "PVP - Event Startet!");
            }    
        }
    }
    if(command.getName().equalsIgnoreCase("PVPEVENToff")) {
        HandlerList.unregisterAll();
    }
    return true;
}

@EventHandler
public void onRespawnPVPEVENT(PlayerRespawnEvent pvpevent ) {
    Player p = pvpevent.getPlayer();
    double x = 48.69925614938256;
    double y = 7.0;
    double z = 47.4376551334051;
    Location loc = new Location(Bukkit.getWorld("world"), x, y, z);
    pvpevent.setRespawnLocation(loc);
    p.sendMessage("");


}

@EventHandler
public void sed(PlayerDeathEvent totevent) {
    Player p1 = totevent.getEntity();
    p1.sendMessage(ChatColor.GOLD + "[PvP Event] " + ChatColor.AQUA + "Du Bist Gestorben und somit raus");
}

Solution

  • Use the label (which is the command) and after that parse the arguments. Like the following:

    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        if(!(sender instanceOf Player)) {
            sender.sendMessage("Only a player can use this command");
            return true;
        }
        Player player = (Player) sender;
        if(label.equalsIgnoreCase("pvpevent") {
            if(args.length == 0) {
                player.sendMessage("Use: /pvpevent on/off");
                return true;
            } else if(args.length == 1) {
                String mode = args[0];
                if(mode.equalsIgnoreCase("on") {
                    Bukkit.getPluginManager().registerEvents(this, this);
                    //what you want on /pvpevent on
                    return true;
                } else if(mode.equalsIgnoreCase("off") {
                    HandlerList.unregisterAll(this);
                    //what you want to do if /pvpevent off is entered.
                    return true;
                } else {
                    //what is called when not off/on is entered after /pvpevent
                }
            }
        }
        return false;
    }
    

    So what we do here is checking if the arg length is 0 if it is 0 you send the actual usage. After that we check what the first argument after /pvpevent is.