NameTagItem .java

net.minecraft.world.item.NameTagItem (class, 35 lines): extends Item. members: interactLivingEntity. imports: Mob.

net.minecraft.world.itemclass35 linescommonextends Item1.0 KB

API Surface (1)

InteractionResult interactLivingEntity(final ItemStack itemStack, final Player player, final LivingEntity target, final InteractionHand type)

Full Source

NameTagItem.java35 lines · Minecraft 26.3 · verbatim
1
package net.minecraft.world.item;
2
3
import net.minecraft.core.component.DataComponents;
4
import net.minecraft.network.chat.Component;
5
import net.minecraft.world.InteractionHand;
6
import net.minecraft.world.InteractionResult;
7
import net.minecraft.world.entity.LivingEntity;
8
import net.minecraft.world.entity.Mob;
9
import net.minecraft.world.entity.player.Player;
10
11
public class NameTagItem extends Item {
12
	public NameTagItem(final Item.Properties properties) {
13
		super(properties);
14
	}
15
16
	@Override
17
	public InteractionResult interactLivingEntity(final ItemStack itemStack, final Player player, final LivingEntity target, final InteractionHand type) {
18
		Component customName = itemStack.get(DataComponents.CUSTOM_NAME);
19
		if (customName != null && target.getType().canSerialize()) {
20
			if (!player.level().isClientSide() && target.isAlive()) {
21
				target.setCustomName(customName);
22
				if (target instanceof Mob mob) {
23
					mob.setPersistenceRequired();
24
				}
25
26
				itemStack.shrink(1);
27
			}
28
29
			return InteractionResult.SUCCESS;
30
		} else {
31
			return InteractionResult.PASS;
32
		}
33
	}
34
}
35

Decompiled Minecraft 26.3 source of NameTagItem (net/minecraft/world/item/NameTagItem.java) with Mojang official mappings, stored verbatim on the site.