Skip to content

Instantly share code, notes, and snippets.

@aadnk
Created January 20, 2013 18:06
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aadnk/4580362 to your computer and use it in GitHub Desktop.
Save aadnk/4580362 to your computer and use it in GitHub Desktop.
Apply an enchanting glow without actually adding any enchantments.
package com.comphenix.example;
import java.lang.reflect.Field;
import net.minecraft.server.v1_4_R1.ItemStack;
import net.minecraft.server.v1_4_R1.NBTTagCompound;
import net.minecraft.server.v1_4_R1.NBTTagList;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.craftbukkit.v1_4_R1.inventory.CraftItemStack;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
public class GlowWithEnchanting extends JavaPlugin {
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (sender instanceof Player) {
Player player = (Player) sender;
CraftItemStack test = CraftItemStack.asCraftCopy(new org.bukkit.inventory.ItemStack(Material.IRON_AXE, 1));
addGlow(test);
player.getInventory().addItem(test);
}
return true;
}
private void addGlow(org.bukkit.inventory.ItemStack stack) {
ItemStack nmsStack = (ItemStack) getField(stack, "handle");
NBTTagCompound compound = nmsStack.tag;
// Initialize the compound if we need to
if (compound == null) {
compound = new NBTTagCompound();
nmsStack.tag = compound;
}
// Empty enchanting compound
compound.set("ench", new NBTTagList());
}
private Object getField(Object obj, String name) {
try {
Field field = obj.getClass().getDeclaredField(name);
field.setAccessible(true);
return field.get(obj);
} catch (Exception e) {
// We don't care
throw new RuntimeException("Unable to retrieve field content.", e);
}
}
}
@Wundark
Copy link

Wundark commented Aug 31, 2013

Thank you!

@XyperCode
Copy link

Won't work anymore in 1.16.
Instead of the line nbt.set("ench", new NBTTagCompound());
You need to use: nbt.set("Enchantments", new NBTTagCompound());

@nathanfranke
Copy link

Using NMS libraries directly forces you to have a fixed version. Instead, use reflection or built-in bukkit/spigot methods.

What I do personally for enchantment is add a dummy effect (Aqua Affinity I) and the HIDE_ENCHANTS item flag.

item.addUnsafeEnchantment(Enchantment.WATER_WORKER, 1);
ItemMeta meta = item.getItemMeta();
meta.addItemFlags(ItemFlag.HIDE_ENCHANTS);
item.setItemMeta(meta);

@Vap0r1ze
Copy link

Vap0r1ze commented Feb 4, 2021

@nathanfranke I love your solution, thank you for posting it. Had no idea about item flags until now!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment