[Solved] Getting Display Name From: InteractEntityEvent.Primary.MainHand Event

Sounds simple, but yet I can’t figure out how to obtain the display name of a spawned NPC, which has a DISPLAY_NAME, from a InteractEntityEvent.Primary.MainHand event. I entered a couple of debug messages, and it returned entity NPC as unknown. I know the problem starts there, but I don’t understand why it is unknown. Any help would be appreciated :slight_smile:

@Listener
public void onPlayerInteractBlock(InteractEntityEvent.Primary.MainHand event, @First Player player){
	
	Entity NPC = event.getTargetEntity();		
	
	Player PNPC = (Player)NPC;		
	
	String displayName = PNPC.getDisplayNameData().displayName().toString();

Try just calling .getName. Also, make sure to check if the NPC is actually an instanceof Player. Also, your method is named InteractBlock, but you’re listening to InteractEntity. Also also, java conventions say all non-static-final variables should be named with camelCase (start lowercase, subsequent words uppercase).

As mentioned, my problem starts when I try to get the entity that I’m interacting with. If. If it helps, the entity was created using an entity type HUMAN. I forgot to change the name of the method when I copied it from another listener, thanks. I’m aware of the JAVA conventional ways of naming things, but I was thinking about addressing details, such as these, once the plugin was ready for release.

It’s almost definitely fixed by using getName(), since players don’t necessarily have display names. And on the topic of conventions, the idea is that you don’t name them incorrectly in the first place, that it’s natural for you to name them with proper conventions. This way, there’s nothing to go back and correct.

1 Like

Figured it out. For those who might seek similar solutions:

@Listener
public void onDZNPCInteract(InteractEntityEvent.Primary.MainHand event, @First Player player) throws ObjectMappingException{
	
	Optional<Text> DN = event.getTargetEntity().get(Keys.DISPLAY_NAME);
	
	if(DN.isPresent()){
		
		Text displayN = DN.get();
		
		String displayName = displayN.toPlain();
	}
}