Howto get Item name from Entity

Hi, Im trying get item name of dropped item.

@Listener
public void PlayerDropItemEvent(DropItemEvent.Dispense event) {

Entity drop = event.getEntities().get(0);
System.out.println("debug "+ drop)

in the log:
EntityItem[‘item.tile.steamadvantage.steam_pipe’/200, l=‘world’, x=63,00, y=73,32, z=-157,00]

How i can get name from the Entity? (item.tile.steamadvantage.steam_pipe) or translated string (Brass Pipe) ?

1 Like
System.out.println("EntityType id: " + drop.getType().getId());
System.out.println("Entity translation id: " + drop.getType().getTranslation().getId());

first line print “minecraft:item”
second line throw exception :frowning:

Ok, so two things:

  1. Item entities are still just EntityType.ITEMs. If you want to get the ItemStack information, you’ll need to query for the ItemStackSnapshot with the Data API, @Saladoc should be able to help you with that one.
  2. An error on the second line likely means that translations are still not working or partially implemented, so if there’s not an issue on the repository, make one please :).

The code snippet by @gabizou only gets you the entity type. Using the Data API you can obtain the ItemStack represented by this entity like this:

Optional<ItemStack> stack = entity.get(Keys.REPRESENTED_ITEM);
if (stack.isPresent()) {
    System.out.println(stack.get().getType().getId());
}

Or (a little shorter)

entity.get(Keys.REPRESENTED_ITEM).ifPresent(item -> System.out.println(item.getType().getId()));

Whenever you can’t find how to get something from a DataHolder, its probably somewhere in the Data API. So it always pays off to take a look at the Keys that exist in SpongeAPI.

1 Like

Many thanks!

Works for me now.