8,240 bytes added
, 07:43, 10 June 2022
Block entities are like simplified entities that are bound to a <code>Block</code>. They are used to store dynamic data, execute tick based tasks and for dynamic rendering. Some examples from vanilla Minecraft would be: handling of inventories (chests), smelting logic on furnaces, or area effects for beacons. More advanced examples exist in mods, such as quarries, sorting machines, pipes, and displays.
{{Colored box|title=Tip|content=A <code>BlockEntity</code> isn’t a solution for everything, and they can cause lag when used wrongly. When possible, try to avoid them.}}
== Creating a <code>BlockEntity</code> ==
In order to create a <code>BlockEntity</code> you need to extend the <code>BlockEntity</code> class. To register it, listen for the appropriate registry event and create a <code>BlockEntityType</code>:
<syntaxhighlight lang="java">
@SubscribeEvent
public static void registerTE(RegistryEvent.Register<BlockEntityType<?>> evt) {
BlockEntityType<?> type = BlockEntityType.Builder.of(supplier, validBlocks).build(null);
type.setRegistryName("examplemod", "mybe");
evt.getRegistry().register(type);
}
</syntaxhighlight>
You can also use a <code>DeferredRegister</code> instead.
<syntaxhighlight lang="java">
public static final DeferredRegister<BlockEntityType<?>> BLOCK_ENTITIES = DeferredRegister.create(ForgeRegistries.BLOCK_ENTITIES, "examplemod");
public static final RegistryObject<BlockEntityType<?>> MY_BE = BLOCK_ENTITIES.register("mybe", () -> BlockEntityType.Builder.of(supplier, validBlocks).build(null));
</syntaxhighlight>
In this example, <code>supplier</code> is a <code>BlockEntityType$BlockEntitySupplier</code> that creates a new instance of your <code>BlockEntity</code>. A method reference or a lambda is commonly used. The variable <code>validBlocks</code> is one or more blocks (<code><nowiki>BlockEntityType$Builder::of</nowiki></code> is varargs) that the block entity can exist for.
== Attaching a <code>BlockEntity</code> to a <code>Block</code> ==
To attach your new <code>BlockEntity</code> to a <code>Block</code>, the <code>EntityBlock</code> interface must be implemented on your <code>Block</code> subclass. The method <code>EntityBlock#newBlockEntity(BlockPos, BlockState)</code> must be implemented and return a new instance of your <code>BlockEntity</code>.
== Storing Data within your <code>BlockEntity</code> ==
In order to save data, override the following two methods
<syntaxhighlight lang="java">
BlockEntity#saveAdditional(CompoundTag tag)
BlockEntity#load(CompoundTag tag)
</syntaxhighlight>
These methods are called whenever the <code>LevelChunk</code> containing the <code>BlockEntity</code> gets loaded from/saved to a tag. Use them to read and write to the fields in your block entity class.
{{Colored box|title=Tip|content=Whenever your data changes you need to call <code><nowiki>BlockEntity#setChanged()</nowiki></code>, otherwise the <code>LevelChunk</code> containing your <code>BlockEntity</code> might be skipped while the level is saved.}}
{{Tip/Important|It is important that you call the super methods!
The tag names <code>id</code>, <code>x</code>, <code>y</code>, <code>z</code>, <code>ForgeData</code> and <code>ForgeCaps</code> are reserved by the super methods.}}
== Ticking <code>BlockEntity</code> ==
If you need a ticking <code>BlockEntity</code>, for example to keep track of the progress during a smelting process, another method must be implemented and overridden within <code>EntityBlock</code>: <code>EntityBlock#getTicker(Level, BlockState, BlockEntityType)</code>. This can implement different tickers depending on which logical side the user is on, or just implement one general ticker. In either case, a <code>BlockEntityTicker</code> must be returned. Since this is a functional interface, it can just take in a method representing the ticker instead:
<syntaxhighlight lang="java">
// Inside some Block subclass
@Nullable
@Override
public <T extends BlockEntity> BlockEntityTicker<T> getTicker(Level level, BlockState state, BlockEntityType<T> type) {
return type == MyBlockEntityTypes.MY_BE.get() ? MyBlockEntity::tick : null;
}
// Inside MyBlockEntity
public static void tick(Level level, BlockPos pos, BlockState state, T blockEntity) {
// Do stuff
}
</syntaxhighlight>
{{Colored box|title=Tip|content=This method is called each tick. Therefore, you should avoid having complicated calculations in here. If possible, you should make more complex calculations just every X ticks. (The amount of ticks in a second may be lower than 20 (twenty) but won’t be higher)}}
== Synchronizing the Data to the Client ==
There are 3 (three) ways of syncing data to the client. Synchronizing on chunk load, synchronizing on block updates and synchronizing with a custom network message.
=== Synchronizing on LevelChunk load ===
For this you need to override
<syntaxhighlight lang="java">
BlockEntity#getUpdateTag()
IForgeBlockEntity#handleUpdateTag(CompoundTag tag)
</syntaxhighlight>
Again, this is pretty simple, the first method collects the data that should be send to the client, while the second one processes that data. If your <code>BlockEntity</code> doesn’t contain much data you might be able to use the methods out of the [[#storing data/1.18|Storing Data]] section.
{{Tip/Important|Synchronizing excessive/useless data for block entities can lead to network congestion. You should optimize your network usage by sending only the information the client needs when the client needs it. For instance, it is more often than not unnecessary to send the inventory of a block entity in the update tag, as this can be synchronized via its <code>AbstractContainerMenu</code>.)}}
=== Synchronizing on block update ===
This method is a bit more complicated, but again you just need to override 2 or 3 methods. Here is a tiny example implementation of it:
<syntaxhighlight lang="java">
@Override
public CompoundTag getUpdateTag() {
CompoundTag tag = new CompoundTag();
//Write your data into the tag
return tag;
}
@Override
public Packet<ClientGamePacketListener> getUpdatePacket() {
// Will get tag from #getUpdateTag
return ClientboundBlockEntityDataPacket.create(this);
}
// Can override IForgeBlockEntity#onDataPacket. By default, this will defer to the #load.
</syntaxhighlight>
The static constructors <code>ClientboundBlockEntityDataPacket#create</code> takes:
* The <code>BlockEntity</code>.
* An optional function to get the <code>CompoundTag</code> from the <code>BlockEntity</code>. By default, this uses <code>BlockEntity#getUpdateTag</code>.
Now, to send the packet, an update notification must be given on the server.
<code>
Level#sendBlockUpdated(BlockPos pos, BlockState oldState, BlockState newState, int flags)
</code>
The <code>pos</code> should be your <code>BlockEntity</code>’s position. For <code>oldState</code> and <code>newState</code> you can pass the current <code>BlockState</code> at that position. The <code>flags</code> are a bitmask and should contain <code>2</code>, which will sync the changes to the client. See <code>Block</code> for more info as well as the rest of the flags. The flag <code>2</code> is equivalent to <code><nowiki>Block#UPDATE_CLIENTS</nowiki></code>.
=== Synchronizing using a custom network message ===
This way of synchronizing is probably the most complicated one, but is usually also the most optimized one, as you can make sure that only the data you need to be synchronized is actually synchronized. You should first check out the <code>[[Understanding Networking/1.18|Networking]]</code> section and especially <code>[[Using SimpleChannel/1.18|SimpleImpl]]</code> before attempting this. Once you’ve created your custom network message, you can send it to all users that have the <code>BlockEntity</code> loaded with:
<syntaxhighlight lang="java">
SimpleChannel#send(PacketDistributor.TRACKING_CHUNK.with(() -> chunk), MSG);
</syntaxhighlight>
{{Colored box|title=Alert|content=It is important that you do safety checks, the <code>BlockEntity</code> might already be destroyed/replaced when the message arrives at the player! You should also check if the area is loaded using (<code><nowiki>Level#hasChunkAt(BlockPos)</nowiki></code>)}}