onCommand

Discussion in 'Plugin Development' started by sajmonks, Jul 14, 2014.

Thread Status:
Not open for further replies.
  1. Hello. I have a little problem, because i always used to use events to detect command s(PlayerCommandPreprocessEvent). I really have to use onCommand, and i wanted to try out sample
    Code:
     public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args){
         Player target = this.getPlayerFromName(args[0]);
        if (target == null) {
            sender.sendMessage(args[0] + " is not online!");
            return false;
        }
        return false;
     }
    but it doesn't work, like this method don't even execute when i am writing any command. Please help.
     
  2. Offline

    xAstraah

    sajmonks, Here is a little example:

    Code:java
    1. public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) {
    2. if(!(sender instanceof Player)) {
    3. sender.sendMessage("You are not a Player!");
    4. return true;
    5. }
    6.  
    7. Player p = (Player) sender;
    8.  
    9. if(command.getName().equalsIgnoreCase("CommandName")) {
    10. //Do stuff here.
    11. }
    12.  
    13. return false;
    14. }
     
  3. Offline

    Necrodoom

    Have you registered a command in the plugin.yml?
    Why are you checking args[0] before checking if it exists?
    getPlayerFromName? You mean getPlayer?
     
  4. Offline

    Zettelkasten

    The problem is that you need to specify the commands your method should listen for, otherwise it will not work.

    This is how you add an command:
    1. Add the command to your plugin.yml:
    Code:
    main: your.main.class.is.awesome
    [...]
    commands:
      isonline:
        description: Checks if a player is online.
        usage: /isonline <player>
    This would add the command "isonline".

    2. Make a command executor (that is a class that implements CommandExecutor and has the onCommand(...) method):
    This would be your class in the example. If this is not your plugin class, initilise it using:
    Code:
    CommandExecutor commandExecutor = new WhatEverYourClassIsCalled();
    If it is the plugin class, you can just use "this" in step 3.

    3. Register it in the plugin code (when the plugin is enabled, for example in onEnable()):
    Code:
    getCommand("isonline").setExecutor(commandExecutor);
    // or
    getCommand("isonline").setExecutor(this);
     
Thread Status:
Not open for further replies.

Share This Page