User Tools

Site Tools


tutorial:extendedscreenhandler

This is an old revision of the document!


Syncing Custom Data with Extended ScreenHandlers

In this tutorial we will use the ExtendedScreenHandler to transfer arbitary data from the Server to the Client ScreenHandler when the ScreenHandler is opened.

In our example we will send the position of the block and render it as the containers title

To understand this tutorial you need to read the first Screenhandler tutorial. Methods which have no code here were already shown in that tutorial

BlockEntity

As the Block class does not need to be changed at all we leave it out here.

BoxBlockEntity.java
  1. public class BoxBlockEntity extends BlockEntity implements ExtendedScreenHandlerFactory, ImplementedInventory {
  2. private final DefaultedList<ItemStack> inventory = DefaultedList.ofSize(9, ItemStack.EMPTY);
  3.  
  4. public BoxBlockEntity() {
  5. super(Test.BOX_BLOCK_ENTITY);
  6. }
  7.  
  8.  
  9. //From the ImplementedInventory Interface
  10.  
  11. @Override
  12. public DefaultedList<ItemStack> getItems() {
  13. return inventory;
  14.  
  15. }
  16.  
  17. //These Methods are from the NamedScreenHandlerFactory Interface
  18.  
  19. @Override
  20. public @Nullable ScreenHandler createMenu(int syncId, PlayerInventory playerInventory, PlayerEntity player) {
  21. //We provide this to the screenHandler as our class Implements Inventory
  22. //Only the Server has the Inventory at the start, this will be synced to the client in the ScreenHandler
  23. return new BoxScreenHandler(syncId, playerInventory, this);
  24. }
  25.  
  26. @Override
  27. public Text getDisplayName() {
  28. return new TranslatableText(getCachedState().getBlock().getTranslationKey());
  29. }
  30.  
  31. //This Method is from the ExtendedScreenHandlerFactory
  32.  
  33. //This method gets called on the Server when it requests the client to open the screenHandler.
  34. //The contents you write into the packetByteBuf will automatically be transferred in a packet to the client
  35. //and the ScreenHandler Constructor with the packetByteBuf argument gets called on the client
  36. //
  37. //The order you insert things here is the same as you need to extract them. You do not need to reverse the order!
  38. @Override
  39. public void writeScreenOpeningData(ServerPlayerEntity serverPlayerEntity, PacketByteBuf packetByteBuf) {
  40. //The pos field is a public field from BlockEntity
  41. packetByteBuf.writeBlockPos(pos);
  42. }
  43. }
tutorial/extendedscreenhandler.1597421593.txt.gz · Last modified: 2020/08/14 16:13 by manymoney2