Store NBT data at block locations using chunk persistence
The NBTBlock class provides a helper to store NBT data at block locations. Since non-BlockEntity blocks cannot have NBT data, this class stores the data in the chunk instead.
NBTBlock is only available for Minecraft 1.16.4+. It will throw an NbtApiException on older versions.
The data is stored at the location, not on the block itself. If the block is broken, changed, exploded, or moved, the data remains at that location.
Returns the NBTCompound for this block location. Creates a new compound if one doesn’t exist.The data is stored in the chunk’s persistent data container under blocks.X_Y_Z where X, Y, Z are the block coordinates.
NBTBlock nbtBlock = new NBTBlock(block);NBTCompound data = nbtBlock.getData();// Now you can read/write NBT datadata.setString("owner", "Steve");data.setInteger("level", 5);
Block block = location.getBlock();NBTBlock nbtBlock = new NBTBlock(block);NBTCompound data = nbtBlock.getData();// Store custom datadata.setString("owner", player.getName());data.setLong("placedTime", System.currentTimeMillis());data.setBoolean("protected", true);data.setInteger("level", 1);player.sendMessage("Block data saved!");
Block block = event.getBlock();NBTBlock nbtBlock = new NBTBlock(block);NBTCompound data = nbtBlock.getData();// Remove specific keyif (data.hasTag("owner")) { data.removeKey("owner");}// Or clear all datafor (String key : new HashSet<>(data.getKeys())) { data.removeKey(key);}player.sendMessage("Block data cleared");
Block block = location.getBlock();NBTBlock nbtBlock = new NBTBlock(block);NBTCompound data = nbtBlock.getData();// Store a list of players who interactedNBTCompoundList visitors = data.getCompoundList("visitors");NBTListCompound visitor = visitors.addCompound();visitor.setString("name", player.getName());visitor.setString("uuid", player.getUniqueId().toString());visitor.setLong("time", System.currentTimeMillis());// Store custom configurationNBTCompound config = data.getOrCreateCompound("config");config.setBoolean("autoCollect", true);config.setInteger("radius", 5);config.setDouble("multiplier", 1.5);
// GOOD - Single access to NBT dataNBTBlock nbtBlock = new NBTBlock(block);NBTCompound data = nbtBlock.getData();data.setString("key1", "value1");data.setString("key2", "value2");data.setString("key3", "value3");// AVOID - Multiple NBTBlock creationsfor (String key : keys) { NBTBlock nbtBlock = new NBTBlock(block); // Creates new instance each time NBTCompound data = nbtBlock.getData(); data.setString(key, values.get(key));}// BETTER - Reuse the data compoundNBTBlock nbtBlock = new NBTBlock(block);NBTCompound data = nbtBlock.getData();for (String key : keys) { data.setString(key, values.get(key));}