Created
January 20, 2013 18:06
-
-
Save aadnk/4580362 to your computer and use it in GitHub Desktop.
Apply an enchanting glow without actually adding any enchantments.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
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());
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);
@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
Thank you!