Changes

588 bytes added ,  03:01, 10 March 2023
→‎Registering Packets: fix errors and demonstrate new builder
Line 38: Line 38:     
<syntaxhighlight lang="java">
 
<syntaxhighlight lang="java">
// A class MessagePacket
+
class MessagePacket {
public void encoder(FriendlyByteBuf buffer) {
+
  public void encoder(FriendlyByteBuf buffer) {
  // Write to buffer
+
      // Write to buffer
}
+
  }
 +
 
 +
  public static MessagePacket decoder(FriendlyByteBuf buffer) {
 +
      // Create packet from buffer data
 +
  }
   −
public static MessagePacket decoder(FriendlyByteBuf buffer) {
+
  public void messageConsumer(Supplier<NetworkEvent.Context> ctx) {
  // Create packet from buffer data
+
      // Handle message
 +
  }
 
}
 
}
   −
public void messageConsumer(Supplier<NetworkEvent.Context>> ctx) {
+
// Original direct registration syntax
  // Handle message
+
INSTANCE.registerMessage(id, MessagePacket.class,
}
+
  MessagePacket::encoder,
 +
  MessagePacket::decoder,
 +
  MessagePacket::messageConsumer);
 +
  // Consumer here must use enqueueWork and setPacketHandled
   −
// For some SimpleChannel channel
+
// New builder-based definition
channel.registerMessage(id, MessagePacket::encoder, MessagePacket::decoder, MessagePacket::messageConsumer);
+
INSTANCE.messageBuilder(MessagePacket.class, id)
 +
  .encoder(MessagePacket::encoder)
 +
  .decoder(MessagePacket::decoder)
 +
  .consumerMainThread(MessagePacket::messageConsumer);
 +
// You can use consumerMainThread or consumerNetworkThread.
 +
// If you use consumerMainThread, the builder will take care of the enqueueWork and setPacketHandled.
 +
// With consumerNetworkThread, you can return a value instead of calling setPacketHandled.
 
</syntaxhighlight>
 
</syntaxhighlight>
  
4

edits