-
Notifications
You must be signed in to change notification settings - Fork 2
Method Hooks
When you've written your command's specification in the command file and given it the hook
tag, you're ready to implement it. This step requires us to use a platform implementation, so for this tutorial we will be using Spigot. The process is nearly identical for other platforms, with the only major difference being that the spigot platform uses the CommandSender
class as its sender type, and other platforms will use a different type.
To get started, let's first bring back our command file from before:
add int:a int:b {
help = Adds two numbers together
hook = add
}
We need to start by parsing the command file. On the Spigot platform, we first get the command manager, and can then get a command parser from that. You can do this with the following code in your onEnable (on other platforms, use your initialization equivalent):
@Override
public void onEnable() {
// Shown for clarity. On Spigot, you can use Plugin#getResource to simplify this.
InputStream input = this.getClass().getResourceAsStream("/command.ordn");
SpigotCommandManager.getInstance(this).getParser().setHookTargets(this).parse(input).register();
}
Here, we have created a command manager, then used it to create a command parser. We then set the hook targets - objects which define methods that the commands will hook into. Passing this
means the methods will be in the same class in this case, but you can pass any object. With this in place, we're finally ready to implement our command:
@CommandHook("add")
public void add(CommandSender sender, int a, int b) {
sender.sendMessage(String.valueOf(a + b));
}
And now, if someone runs add 1 2
, they will have the result of the addition sent to them.
The sender is always passed as the first argument to a method hook, followed by arguments. Next up, we'll be learning more about arguments with Subcommands and Advanced Arguments.