bukkit Commands A simple set GameMode command ( /gm )


Example

This example shows a very basic example of how to utilize onCommand. I don't suggest processing your commands directly in onCommand, but this does the trick for this simple case.

In this example we attempt to set the player's gamemode.

The first thing we need to do is make sure that the sender isn't a ConsoleCommandSender, because we can't set a console's gamemode. This is done with (sender instanceof Player).

Next, we want the player to type /gm CREATIVE (or what ever other gamemode) so we have to check 2 things:

  1. make sure that they pass in 1 argument (CREATIVE)
  2. make sure that their command was "gm"

We accomplished these checks with: args.length == 1 && label.equalsIgnoreCase("gm")

Now we know for sure the player typed "/gm x".

The next thing we need to do is turn args[0] into a GameMode object so that we can apply it to the player. This can be done with GameMode.valueOf(String) However, according to the Java enumeration documentation, if a string is passed into valueOf() that doesn't match an enumeration, it will throw an IllegalArgumentException - so we have to make sure to catch that.

Once we have the gamemode, we can go ahead and simply use p.setGameMode(gm) and the player's gamemode will change. In the case that we caught an exception - we simply print out a statement and return false.

@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
    if (sender instanceof Player) { 
        final Player p = (Player) sender;

        if (args.length == 1 && label.equalsIgnoreCase("gm")) {
            try {
                GameMode gm = GameMode.valueOf(args[0]);
                p.setGameMode(gm);
                p.sendMessage(ChatColor.GREEN + "Your gamemode has been set to: " + gm.toString());
                return true;
            } catch (IllegalArgumentException e) {
                p.sendMessage(ChatColor.RED + "Invalid gamemode option!");
                return false;
            }

        }
    }
    return false;
}