Method to register commands

How would I go about creating a separate method to register my commands? This is what I have so far:

  // I have all of my imports, I just decided not to paste them
@Plugin(id = "me.roboticplayer.helloworld", name = "Hello World", version = "1.0")
public class HelloWorld implements CommandExecutor {

  @Listener
  public void onInitialization(GameInitializationEvent e) {
    registerHello();
  }

  @Override
  public CommandResult execute(CommandSource sender, CommandContext commandcontext) throws CommandException {
    // Temporary!
    return null;
  }

  public void registerHello() {
    CommandSpec hello = CommandSpec.builder().description(Texts.of("Says hello to the sender!")).executor(this)
      .build();

  // Right here I want to put something that will actually register the command
  // If I were in an event, I could do e.getGame().getCommandDispatcher().register(params)
  // But I'm not, and I don't know what methods I can use to get the game/command dispatcher
  }
}

Store a reference to the Game object in your class as a private field.
The simplest way is to @Inject it.

public class HelloWorld implements CommandExecutor {

    @Inject
    private Game game;
[...]
    public void registerHello() {
        CommandSpec hello = CommandSpec.builder().description(Texts.of("Says hello to the sender!")).executor(this)
      .build();
        this.game.getCommandDispatcher().register(hello);
    }
}

You could also pass the game object to registerHello as a parameter but you’ll find it more convenient to use a field.

1 Like

Great, thanks! I’ll try it out.

I recommend reading through the documentation laid out here: https://docs.spongepowered.org/en/plugin/commands/index.html

2 Likes