0

My event handler is running twice when clicking a block event when I check for off hand. I tried to check many of the values that could screw this up but they are always the same. There's my code:

package me.ronking159.jtest.handlers;

import me.ronking159.jtest.items.ItemManager;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.plugin.Plugin;

public class WandHandler implements Listener {
    public WandHandler(Plugin Jtest) {
        Bukkit.getPluginManager().registerEvents(this, Jtest);
    }

    @EventHandler
    public void WandHandler(PlayerInteractEvent event) {
        if (event.getHand().name() != "HAND") return;
//        if (event.getAction().equals(Action.RIGHT_CLICK_BLOCK)) return;
        if (event.getItem() == null) return;
        if (!(event.getItem().getItemMeta().equals(ItemManager.wand.getItemMeta()))) return;

        Player p = event.getPlayer();
        p.getWorld().createExplosion(p.getLocation(), 2.0f);
        p.sendMessage("You don't know how to use a wand yet!");
        p.sendMessage(event.getAction().name());
        p.sendMessage(event.getHand().name());
        p.sendMessage(event.getMaterial().name());
    }
}

Is the answer obvious and I don't get it?

Ron Caspi
  • 1
  • 1
  • Are you sure you're not getting the event with `event.getAction().equals(Action.PHYSICAL)` one of the times? It would be sent from stepping onto pressure plates & etc. ([see here](https://hub.spigotmc.org/javadocs/bukkit/org/bukkit/event/block/Action.html#PHYSICAL)). Otherwise there should be only a single RIGHT_CLICK_BLOCK/_AIR per click, I believe – abel1502 Sep 21 '22 at 18:07

1 Answers1

0

It's firing twice because it does so once for HAND and then OFF_HAND. Your hand check doesn't work because you're checking for reference equality with !=. Read this answer for more information.

You should check the hand like so:

if(e.getHand() != EquipmentSlot.HAND)
    return;

But if you insisted on string comparison, you would do:

if(!e.getHand().name().equals("HAND"))
    return;
Lucan
  • 2,907
  • 2
  • 16
  • 30
  • That was not the problem, though looking into it, when I'm in air and I click a block, it's running it one time for air and one time for block. but it doesn't do it when I'm underwater. – Ron Caspi Sep 22 '22 at 11:44