Enchanting an ItemStack

How would I enchant an ItemStack?

Offer it some EnchantmentData

3 Likes

In case that sounds cryptic, https://docs.spongepowered.org/en/plugin/items.html#modifying-itemstack-data

1 Like

Thanks! Did I do this correctly?

itemStackExample.offer((DataManipulator) Enchantments.FEATHER_FALLING);

Not quite. You need to get the EnchantmentData, add the enchantment to it, and then offer the data back to the item stack.

EnchantmentData data = itemStackExample.getOrCreate(EnchantmentData.class).get();
data.set(data.enchantments().add(Enchantments.FEATHER_FALLING));
itemStackExample.offer(data);

Or you can use the Value API (a part of the Data API) to shorten it:

itemStackExample.offer(itemStackExample.get(Keys.ENCHANTMENTS).get().add(Enchantments.FEATHER_FALLING));
1 Like

It doesn’t work. It says

When I tried the shortened one, it says that it can not resolve Keys.ENCHANTMENTS.

Maybe you’re referring to an old version of the API?

I just messed up some of the code. Here’s a version that should work:

EnchantmentData data = itemStackExample.getOrCreate(EnchantmentData.class).get();
data.set(data.enchantments().add(new ItemEnchantment(Enchantments.FEATHER_FALLING, insertEnchantmentLevelHere)));
itemStackExample.offer(data);

Shorter version:

itemStackExample.offer(itemStackExample.get(Keys.ITEM_ENCHANTMENTS).get().add(new ItemEnchantment(Enchantments.FEATHER_FALLING, insertEnchantmentLevelHere)));

Replace insertEnchantmentLevelHere with the 0-based enchantment level (so Feather Falling I would be 0, Feather Falling II would be 1, etc.)

1 Like

Shortest version :

item.transform(Keys.ITEM_ENCHANTMENTS, (l) -> {
    l.add(new ItemEnchantment(Enchantments.FEATHER_FALLING, level));
    return l;
});

:slight_smile:

1 Like

how can i read the enchantments…