Is it possible to make a pickaxe in Minecraft which breaks certain blocks at a certain location

I'm making a parkour map and my construction site fence is made out of iron bars and I want to make a pickaxe which the player could use inside the construction site but couldn't break the fence. I want to make an obstacle inside the construction site out of iron bars which could be broken with an iron pickaxe that can break iron bars inside the construction site, but not outside of it.


This can be done with 2 repeating command blocks. First command gives the closest player the item:

give @p minecraft:iron_pickaxe{CanDestroy:["iron_bars"],tag:1}

The first command executes only if a player is inside the area in which the pickaxe should work, that's what is determined in the x=... y=... z=... as well as dx=... dy=... dz=...

x y z is the cords and dx dy dz is the size (x=10 and dx=2 would put the starting x at 10 and the end at 12). This is the area in which the obstacle is in, don't make it too small so the player needs to hug the iron bars to destroy them, but not too big so they can reach unwanted iron bars.

The command replaces the player's held item only if the item is a pickaxe and has the tag tag:1. The tag is necessary so the command doesn't continuously give the player a new pickaxe. Then the command /replaceitem replaces the held item with a pickaxe that can break iron bars.

This command needs to be in a repeating command block:

execute if entity @a[x=-12,y=56,z=8,dx=-7,dy=1,dz=-2] as @a[nbt={SelectedItem:
{id:"minecraft:iron_pickaxe",tag:{tag:1}}}] if entity @s 
run replaceitem entity @s weapon.mainhand iron_pickaxe{CanDestroy:["iron_bars"]}

The next command basically does everything opposite of the first command. It only runs for players that aren't in the specified area (make sure you enter the same x y z and dx dy dz in both commands), it then tests for a held pickaxe that can break iron bars and lastly runs the command /replaceitem and gives the player a normal pickaxe with the tag tag:1.

This one does need to be in a repeating command block as well:

execute unless entity @a[x=-12,y=56,z=8,dx=-7,dy=1,dz=-2] 
as @a[nbt={SelectedItem:{id:"minecraft:iron_pickaxe",tag:
{CanDestroy:["iron_bars"]}}}] if entity @s run replaceitem 
entity @s weapon.mainhand iron_pickaxe{tag:1}

The commands don't affect a player that doesn't have the special pickaxe, so you can create different ones later on with different tags.

Important note

/replaceitem will be removed in 1.17 and replaced with /item. However, you can easily convert to the new command, instead of:

/replaceitem entity @s weapon.mainhand iron_pickaxe{tag:1}

it will be:

/item entity @s weapon.mainhand replace iron_pickaxe{tag:1}