How to get the item the CommandSender is holding?

Discussion in 'Spigot Plugin Development' started by teeter11, Jul 12, 2015.

  1. How can you get the item that the command sender is holding?

    import org.bukkit.command.Command;
    import org.bukkit.command.CommandSender;
    import org.bukkit.entity.Player;
    import org.bukkit.plugin.java.JavaPlugin;

    public class UnbreakingMain extends JavaPlugin {

    @Override
    public boolean onCommand(CommandSender sender, Command cmd,String label, String[] args){
    if (cmd.getName().equalsIgnoreCase("unbreakable")){


    }
    }

    }
     
  2. Step 1: Make sure the sender is actually a player
    Step 2: player.getItemInHand()
    Step 3: Profit ;)
     
  3. Sorry im kinda new to this but, I get the error :

    Cannot make a static reference to the non-static method getItemInHand() from the type HumanEntity
     
  4. Mind posting what you did? Also, after you check to see if the sender is a player, you need to cast Player to CommandSender
     
  5. import org.bukkit.command.Command;
    import org.bukkit.command.CommandSender;
    import org.bukkit.entity.Player;
    import org.bukkit.entity.*;
    import org.bukkit.inventory.ItemStack;
    import org.bukkit.plugin.java.JavaPlugin;

    public class UnbreakingMain extends JavaPlugin {

    public void onEnable(){

    }
    @Override
    public boolean onCommand(CommandSender sender, Command cmd,String label, String[] args){
    if (cmd.getName().equalsIgnoreCase("unbreakable")){
    if (!(sender instanceof Player)) {

    return true;
    }
    Player s = (Player) sender;

    Player.getItemInHand()
    // im going to do more with this
    }
    return false;
    }

    }
     
  6. You need to call it from your variable "s". The method getItemInHand() is not a static method, yet you're calling it in a static way.
     
  7. Okay that worked! Im an idiot for not realizing that, thanks!
     
    • Like Like x 1
  8. I'm in my phone, too lazy to type all out, but you should be able to see what I'm doing.

    Code (Text):
    onCommand {
      if (sender instanceof Player) {
        Player p = (Player) sender;
    // Do stuff with p.getItemInHand();
    }
    }