Minecraft – How to use the CanPlaceOn tag on a mob drop

minecraft-commandsminecraft-java-edition

I am making an adventure map in 1.9 and while I know exactly how CanPlaceOn
works, I want to know how I can edit a drop of a mob which has a CanPlaceOn tag in it.

Example: I want to spawn a zombie which drops a lever or a button that can only be placed on certain blocks. Ive been messing with codes already and I cant seem to spawn a zombie which drops a lever with the CanPlaceOn tag in it.

Best Answer

Use a loot table

The best way to do this is using custom loot tables and the set_nbt function. The following loot_table makes a mob drop a single lever that can be placed on diamond blocks.

{
    "pools":[
        {
            "rolls":1,
            "entries":[
                {
                    "type":"item",
                    "name":"minecraft:lever",
                    "weight":1,
                    "functions":[
                        {
                            "function":"set_nbt",
                            "tag":"{CanPlaceOn:[\"minecraft:diamond_block\"]}"
                        }
                    ]
                }
            ]
        }
    ]
}

Loot tables look fairly complicated, but that's because they are extremely powerful and versatile (take a look at the default dungeon chest loot table for example). Luckily, you can find loot table generators like this one by MrPingouin on the web.

What happens here is that there is only one category of items (a "pool"), from which 1 item is randomly chosen ("rolls"). The pool only contains a single item ("entry"), which is our lever. The set_nbt function is used to set the NBT data of the lever to include the CanPlaceOn tag, set to diamond blocks.

Once you have generated your loot table, download it and save it in <map folder>/data/loot_tables/<some folder>/<some name>.json.

To use it in the game, you can use the DeathLootTable data tag in your summon command, e.g.

/summon Zombie ~ ~ ~ {DeathLootTable:"<some folder>:<some name>"}