Skip to content

Block Data Manager

Redempt edited this page Jan 27, 2022 · 6 revisions

The API Spigot has for attaching data to blocks is, while useful, incomplete. RedLib seeks to offer an alternative to this with a simple API that allows you to add data to blocks that will last between restarts, gets moved if the block is moved, and gets deleted if the block is broken.

Using this API is incredibly simple. All you have to do is instantiate a BlockDataManager.

private BlockDataManager manager;

@Override
public void onEnable() {
	manager = BlockDataManager.createAuto(this, this.getDataFolder().toPath().resolve("blocks.db"), true, true);
}

@Override
public void onDisable() {
	manager.saveAndClose();
}

createAuto will use the version of your server to determine whether to use SQLite (for versions below 1.14) or PersistentDataContainer (for versions 1.14+). Calling saveAndClose on the manager will save to the database and close the connection, so put it in your onDisable. If you want to save on an interval, you should call save().

Once you have a BlockDataManager, you can use one of two methods to get a DataBlock, which is how you attach data to blocks. The first method is getDataBlock(Block), which will return a DataBlock at that block, creating an empty one if it doesn't exist. The second method is getDataBlock(Block, boolean), which lets you specify whether to create a new one or return null if it's not already present.

With a DataBlock, you can attach data easily. Let's say you want to make a battery:

Block block; //Assume this value is initialized
DataBlock db = manager.getDataBlock(block);
db.set("charge", 100);

This will set the charge value to 100. At any point later, you can check the value of this field like this:

DataBlock db = manager.getExisting(block);
if (db != null) {
	int charge = db.getInt("charge");
}

Note that you cannot store any types that are not primitives, strings, JSONMaps, or JSONLists directly in DataBlocks, so please serialize them.

And that's really all there is to it! For further reading on how to use the BlockDataManager, you can find the javadocs at https://redempt.dev/javadoc/com/github/Redempt/RedLib/redempt/redlib/blockdata/BlockDataManager.html.

Clone this wiki locally