Skip to content

Instantly share code, notes, and snippets.

@ItsLiyua
Created January 16, 2021 22:57
Show Gist options
  • Save ItsLiyua/2a4a34af02de530b44225f614e5cca9a to your computer and use it in GitHub Desktop.
Save ItsLiyua/2a4a34af02de530b44225f614e5cca9a to your computer and use it in GitHub Desktop.
A method for setting NBT-Tags for items in spigot. Please note, the NBT-Tag with the path "test.helloworld" (for example) will look like this: {test:{helloworld:<data>}}
public class NBTEditor {
public static ItemStack setNBTValue(ItemStack is, String path, String value) {
path = "null." + path;
String[] pathArray = path.split("\\.");
pathArray[0] = null;
net.minecraft.server.v1_16_R3.ItemStack nms = CraftItemStack.asNMSCopy(is);
NBTTagCompound[] nbts = new NBTTagCompound[pathArray.length - 1];
for (int i = 0; i < pathArray.length; i++) {
String part = pathArray[i];
if (i == 0) {
nbts[i] = nms.getOrCreateTag();
} else {
if (i == pathArray.length - 1) {
nbts[i - 1].setString(part, (value == null) ? "" : value);
} else {
nbts[i] = nbts[i - 1].getCompound(pathArray[i]);
}
}
}
for (int i = nbts.length; i-- > 0; ) {
if (i - 1 < nbts.length && i - 1 >= 0) {
nbts[i - 1].set(pathArray[i], nbts[i]);
}
}
nms.setTag(nbts[0]);
return CraftItemStack.asBukkitCopy(nms);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment