Minecraft – How to change one of the enchantment levels of an item to a scoreboard value

minecraft-commandsminecraft-java-edition

I am trying to set up a system on a server I run for my friends where they can trade certain items for points, which can then be traded in for another score representing a certain enchantment and its level which can then be added onto an item of choice. The score system I had no trouble setting up, but I can't seem to get adding the enchantments onto the item from the scoreboard correct

Keeping in mind that I don't want this to be limited to Minecraft's max enchantment values and be unlimited like when giving enchantment nbt to something in a give command. How do I do this? Is there a better way of doing the system that achieves the same thing but in an easier way?

To be clear I do not want a hard-coded solution, I need something dynamic that works with every possible short.

It doesn't need to be edited in the inventory, just edited and returned to the player in some way, even if it means putting it in a chest for them to grab or something along those lines

Best Answer

You can use /data modify and /execute store to make this happen.

If you are using a scoreboard number to represent your enchantment ID, translating it into the NBT string for the enchantment ID will have to be hard-coded. Sorry, there's no way around that.

But for the enchantment level, let's get the magic commands started.

Let's say your item is in a chest at coordinates (12, 23, 34), in slot 0 (the upper left one). You can add an enchantment like so:

/data modify block 12 23 34 Items[{Slot:0b}].tag merge value {Enchantments:[{id:"minecraft:sharpness",lvl:1s}]}

This command should add a single enchantment to the item. The values are for now temporary, but we're about to modify them:

/execute if score @p enchantmentID matches 1 run data modify block 12 23 34 Items[{Slot:0b}].tag.Enchantments[0] merge value {id:"minecraft:smite"}

If ID 1 corresponds to Smite in your map, run this command. Change the values as you wish.

/execute store result block 12 23 34 Items[{Slot:0b}].tag.Enchantments[0].lvl short 1.0 run scoreboard players get @p enchantmentLvl

This means, get the nearest player's score for enchantmentLvl, and store it as a short int in the item's first enchantment.

Remember, neither command can modify player NBT, In layman's terms, you can't modify items still in the inventory. You'll have to get the players to place their item in a chest or other container. For most reliability, have them drop it into a hopper funneling into a chest. This means the item will always end up in slot 0, ensuring you clear the chest after each use.