Search code examples
javaminecraftbukkit

How to choose the block that the item can be placed on?


I would like to know how to choose the block that my TNT be placed on. Here is my code.

ItemStack tnt = new ItemStack(Material.TNT, 1);

As in give @p tnt 1 0 {PlaceOn:emerald_block}.

I am using Spigot for Minecraft 1.12 and Eclipse.


Solution

  • There is no way to do that via the Spigot API natively, you need to use NMS and NBT:

    net.minecraft.server.v1_12_R1.ItemStack stack = CraftItemStack.asNMSCopy(tnt);
    
    NBTTagList tags = (NBTTagList) stack.getTag().get("CanPlaceOn");
    
    if (tags == null)
        tags = new NBTTagList();
    
    tags.add(new NBTTagString("minecraft:emerald_block"));
    
    stack.getTag().set("CanPlaceOn", tags);
    
    ItemStack toUse = CraftItemStack.asCraftMirror(stack);