HandInteractEvent will call the function twice?

@Listener
public void onPlayerMove(HandInteractEvent e, @First Player player) {

	if(player.getItemInHand(HandTypes.MAIN_HAND).get().getItem() == ItemTypes.CLOCK){
		player.sendMessage(Text.of("you use clock"));
	}
}

i don’t know why player.sendMessage(Text.of(“you use clock”)); will be called twice.?
Does anybody know the problem?

if i right click the clock , sometime player.sendMessage(Text.of(“you use clock”)); will be call four times

and , the console will throw expection randomly(sometimes will ,sometimes won’t) if i click with nothing in hand .

Well, this one’s easy.[quote=“Minghao_Liu, post:1, topic:15963”]
.get()
[/quote]

A call to .get() with no value present throws NoSuchElementException. There is nothing in the hand, so no value is present.

As for calling it twice, this will fire both InteractBlockEvent.Secondary.MainHand and InteractBlockEvent.Secondary.OffHand, which both subclass HandInteractEvent. If you only care about the main hand, listen to `InteractBlockEvent.Secondary.MainHand’. For the four-times one, you may be holding right-click too long.

1 Like

Make sure you are using the LATEST Sponge build then do what pie_flavor said.

1 Like

Could also just check the HandType that triggered the event

@Listener
public void onHandInteractEvent(HandInteractEvent event, @First Player player) {
	HandType handType = event.getHandType();
	
	if(handType.equals(HandTypes.MAIN_HAND)) {
		Optional<ItemStack> optionalItem = player.getItemInHand(HandTypes.MAIN_HAND);
		
		if(optionalItem.isPresent()) {
			ItemStack itemStack = optionalItem.get();
			
			if(itemStack.getItem().equals(ItemTypes.CLOCK)) {
				player.sendMessage(Text.of("you use clock"));
			}
		}
	}
}

your code still invoke sendMessage twice ,

i listen InteractBlockEvent.Secondary.MainHand and now the problem solved . : )

got it.

thanks :slight_smile: