Right click with specific item and itemmeta

Discussion in 'Spigot Plugin Development' started by TheGameKing77, Aug 14, 2018.

  1. Hi, i'm trying to make a new food kinda thing, actually it's drugs haha.
    I want that when a player uses right click with the drug in their hand, they get some effects and a message. How does that work? This is my current code:

    Code (Java):
    public class SpeedConsume implements Listener {

        Speed speed = new Speed();

        public void rightClickOnSpeed(PlayerInteractEvent event) {

            //Code here
            Player p = event.getPlayer();
            Action a = event.getAction();

            if ((a == Action.RIGHT_CLICK_AIR) || (a == Action.RIGHT_CLICK_BLOCK)) {

                if ((p.getItemInHand().getType() == Material.SUGAR) && (p.getItemInHand().getItemMeta() == speed.speedMeta)) {

                    //Item is goed, gimme effects
                    p.addPotionEffect(new PotionEffect(PotionEffectType.CONFUSION, 10, 1));
                    p.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, 10, 5));

                    p.sendMessage(ChatColor.RED + "You've used Speed! Bastard!");

                } else {
            } else {


  2. Firstly make sure to handle the case where getItemInMainHand returns null. I think it will do that for an empty hand and your code here will throw an NPE.

    Secondly you can't compare meta directly like that, try using .equals on the two ItemMeta instances instead.
    • Agree Agree x 1
  3. If you have an instance of ItemStack that matches your "speed" item, you can also simply use this to check if the player's item is the same.

    Also, be aware the the event you are looking at is called up to twice, once for the main hand and once for the offhand. Many people simply choose to ignore the offhand events: if(event.getHand() == EquipmentSlot.OFF_HAND) return;

    If you want speed to be used in the offhand too, then use event.getItem() instead of player.getItemInHand(), because otherwise it will check the main hand both times.
    • Agree Agree x 1