7,654 bytes added
, 19:07, 24 October 2020
Tile 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.
<block tip>
A <code>TileEntity</code> isn’t a solution for everything, and they can cause lag when used wrongly. When possible, try to avoid them.
</block>
== Creating a <code>TileEntity</code> ==
In order to create a <code>TileEntity</code> you need to extend the <code>TileEntity</code> class. To register it, listen for the appropriate registry event and create a <code>TileEntityType</code>:
<syntaxhighlight lang="java">
@SubscribeEvent
public static void registerTE(RegistryEvent.Register<TileEntityType<?>> evt) {
TileEntityType<?> type = TileEntityType.Builder.create(factory, validBlocks).build(null);
type.setRegistryName("examplemod", "myte");
evt.getRegistry().register(type);
}
</syntaxhighlight>
You can also use a <code>DeferredRegister</code> instead.
<syntaxhighlight lang="java">
public static final DeferredRegister<TileEntityType<?>> TILE_ENTITIES = DeferredRegister.create(ForgeRegistries.TILE_ENTITIES, "examplemod");
public static final RegistryObject<TileEntityType<?>> MY_TE = TILE_ENTITIES.register("myte", () -> TileEntityType.Builder.create(factory, validBlocks).build(null));
</syntaxhighlight>
In this example, <code>factory</code> is a function that creates a new instance of your <code>TileEntity</code>. A method reference or a lambda is commonly used. The variable <code>validBlocks</code> is one or more blocks (<code><nowiki>TileEntityType$Builder::create</nowiki></code> is varargs) that the tile entity can exist for.
== Attaching a <code>TileEntity</code> to a <code>Block</code> ==
To attach your new <code>TileEntity</code> to a <code>Block</code> you need to override 2 (two) methods within the <code>Block</code> class.
<syntaxhighlight lang="java">
IForgeBlock#hasTileEntity(BlockState state)
IForgeBlock#createTileEntity(BlockState state, IBlockReader world)
</syntaxhighlight>
Using the parameters you can choose if the block should have a <code>TileEntity</code> or not. Usually you will return true in the first method and a new instance of your <code>TileEntity</code> in the second method.
== Storing Data within your <code>TileEntity</code> ==
In order to save data, override the following two methods
<code>
TileEntity#write(CompoundNBT nbt)
TileEntity#read(BlockState state, CompoundNBT nbt)
</code>
These methods are called whenever the <code>Chunk</code> containing the <code>TileEntity</code> gets loaded from/saved to NBT. Use them to read and write to the fields in your tile entity class.
<block tip>
Whenever your data changes you need to call <code><nowiki>TileEntity#markDirty()</nowiki></code>, otherwise the <code>Chunk</code> containing your <code>TileEntity</code> might be skipped while the world is saved.
</block>
<block 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.
</block>
== Ticking <code>TileEntity</code> ==
If you need a ticking <code>TileEntity</code>, for example to keep track of the progress during a smelting process, you need to add the <code><nowiki>ITickableTileEntity</nowiki></code> interface to your <code>TileEntity</code>. Now you can implement all your calculations within
<syntaxhighlight lang="java">
ITickableTileEntity#tick()
</syntaxhighlight>
<block tip>
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)
</block>
== 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 chunk load ===
For this you need to override
<syntaxhighlight lang="java">
TileEntity#getUpdateTag()
IForgeTileEntity#handleUpdateTag(BlockState state, CompoundNBT 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>TileEntity</code> doesn’t contain much data you might be able to use the methods out of the [[#storing_data|Storing Data]] section.
<block important>
Synchronizing excessive/useless data for tile 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 tile entity in the update tag, as this can be synchronized via its GUI.
</block>
=== Synchronizing on block update ===
This method is a bit more complicated, but again you just need to override 2 methods. Here is a tiny example implementation of it
<syntaxhighlight lang="java">
@Override
public SUpdateTileEntityPacket getUpdatePacket(){
CompoundNBT nbtTag = new CompoundNBT();
//Write your data into the nbtTag
return new SUpdateTileEntityPacket(getPos(), -1, nbtTag);
}
@Override
public void onDataPacket(NetworkManager net, SUpdateTileEntityPacket pkt){
CompoundNBT tag = pkt.getNbtCompound();
//Handle your Data
}
</syntaxhighlight>
The Constructor of <code>SUpdateTileEntityPacket</code> takes:
* The position of your <code>TileEntity</code>.
* An ID, though it isn’t really used besides by Vanilla, therefore you can just put a -1 in there.
* An <code>CompoundNBT</code> which should contain your data.
Now, to send the packet, an update notification must be given on the server.
<code>
World#notifyBlockUpdate(BlockPos pos, BlockState oldState, BlockState newState, int flags)
</code>
The <code>pos</code> should be your <code>TileEntity</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>Constants$BlockFlags</code> for more info as well as the rest of the flags. The flag <code>2</code> is equivalent to <code><nowiki>Constants$BlockFlags#BLOCK_UPDATE</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>[[latest:advanced:networking:start|Networking]]</code> section and especially <code>[[latest:advanced:networking:simplechannel|SimpleImpl]]</code> before attempting this. Once you’ve created your custom network message, you can send it to all users that have the <code>TileEntity</code> loaded with:
<syntaxhighlight lang="java">
SimpleChannel#send(PacketDistributor.TRACKING_CHUNK.with(() -> chunk), MSG);
</syntaxhighlight>
<block alert>
It is important that you do safety checks, the TileEntity might already be destroyed/replaced when the message arrives at the player! You should also check if the area is loaded using (<code><nowiki>World#isAreaLoaded(BlockPos, int)</nowiki></code>)
</block>