Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Commoble/c96271da4d8cf4e33f4370eda952f210 to your computer and use it in GitHub Desktop.
Save Commoble/c96271da4d8cf4e33f4370eda952f210 to your computer and use it in GitHub Desktop.
Syncing Tile Entities in Minecraft Forge 1.15
/** TLDR
* Update Tag -> sent when client loads the chunk the TE is in
* Update Packet -> sent when you call world.notifyBlockUpdate
**/
public class YourTileEntity extends TileEntity
{
public YourTileEntity()
{
this(yourTileEntityType);
}
// some data we'll be saving and syncing
public int data;
// we can tell the server to save the TileEntity's state to the hard drive by
// calling someTileEntity.markDirty()
// called to load the TE onto the server from the hard drive
@Override
public void read(CompoundNBT compound)
{
super.read(compound);
this.data = compound.getInt("data");
}
// called to save the TE to the hard drive from the server
@Override
public CompoundNBT write(CompoundNBT compound)
{
CompoundNBT nbt = super.write(compound);
nbt.putInt(this.data);
return nbt;
}
// called to generate NBT for a syncing packet when a client loads a chunk that this TE is in
@Override
public CompoundNBT getUpdateTag()
{
// we want to tell the client about as much data as it needs to know
// since it doesn't know any data at this point, we can usually just defer to write() above
// if you have data that would be written to the disk but the client doesn't ever need to know,
// you can just sync the need-to-know data instead of calling write()
// there's an equivalent method for reading the update tag but it just defaults to read() anyway
return this.write(new CompoundNBT());
}
// we can sync a TileEntity from the server to all tracking clients by calling world.notifyBlockUpdate
// when that happens, this method is called on the server to generate a packet to send to the client
// if you have lots of data, it's a good idea to keep track of which data has changed since the last time
// this TE was synced, and then only send the changed data;
// this reduces the amount of packets sent, which is good
// we only have one value to sync so we'll just write everything into the NBT again
@Override
public SUpdateTileEntityPacket getUpdatePacket()
{
CompoundNBT nbt = new CompoundNBT();
this.write(nbt);
// the number here is generally ignored for non-vanilla TileEntities, 0 is safest
return new SUpdateTileEntityPacket(this.getPos(), 0, nbt);
}
// this method gets called on the client when it receives the packet that was sent in the previous method
@Override
public void onDataPacket(NetworkManager net, SUpdateTileEntityPacket packet)
{
this.read(packet.getNbtCompound());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment