How can I have multiple args in a command like /cmd subcmd {playername}

Discussion in 'Spigot Plugin Help' started by Toxicmine, Jul 10, 2021.

  1. Hi I recoded my Event plugin to make it more cleaner but now Im trying to figure out on how to add a multiple arged command like "/event join {player name}" I already made the "/event join" command but idk how to get the name that they gave while executing the command heres my start class:https://pastebin.com/8z4RH2D9
     
  2. You can get the string args[1] for the third set of characters, and to convert that into a player you can do Bukkit.getPlayer(args[1])
     
  3. I think the best way to do it is just to check if args[0] is equal to what you want and run a method for each option.
    if you want to have multiple options like /event join , /event leave etc... I would do differnet methods for each arg.

    here is an example.

    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
    if (args[0] == "join"){
    joinCommand(sender, cmd, label, args);
    return false;
    }

    if (args[0] == "leave"){
    leaveCommand(sender, cmd, label, args);
    return false;
    }
    (Player) sender.sendMessage("Unknown command"); "you would have to make sure the sender is a player first"
    }

    public void joinCommand (CommandSender sender, Command command, String label, String[]args){
    //Join method
    }

    public void leaveCommand (CommandSender sender, Command command, String label, String[]args){
    //leave method
    }
     
  4. Strahan

    Benefactor

    Your example is not checking if any args were actually passed, so if they just do /command it will crash. You also are using == for String comparison which will not work. You also reference a variable that doesn't exist; cmd. What's the point of passing the command and label anyway? You are also casting sender without verifying it is a Player, and it's pointless anyway. You can do CommandSender#sendMessage so no cast is necessary. I'd also suggest a switch would make for cleaner code. Lastly, if you post code in the future use [CODE] blocks.

    ...but really, I don't think you should until you get some more programming miles under your belt. You'll just end up passing bad practices around.
     
  5. ye poor code cuz i wrote it in here and not on an actual ide but i just showed the way i would do it. also how would the command crash? it wouldnt crash it would just not do anything if you just do /command and you can add a format message at the end if args[0] doesnt match.
    this worked fine for me.
     
  6. Strahan

    Benefactor

    If that's the case, you're better off using pseudocode. The way you wrote the reply is such that a noob developer could pick it up and paste it into their IDE thinking it's good code.

    If you just put "/command" it will crash with an ArrayIndexOutOfBoundsException since you aren't validating args.