接下來我們建立一個新的資料夾叫network,然後建立一個新的class 叫OpenCustomGuiPacket,我們這樣寫
public class OpenCustomGuiPacket {
public static final Identifier ID = new Identifier(TheClassicofMountainsandOceans.MOD_ID,"opengui");
public static void sendToClient(ServerPlayerEntity player) {
PacketByteBuf buf = new PacketByteBuf(Unpooled.buffer());
ServerPlayNetworking.send(player, ID, buf);
}
public static void registerReceiver() {
ClientPlayNetworking.registerGlobalReceiver(ID, (client, handler, buf, responseSender) -> {
client.execute(() -> {
MinecraftClient.getInstance().setScreen(new CustomScreen(
new CustomScreenHandler(0, MinecraftClient.getInstance().player.getInventory()),
MinecraftClient.getInstance().player.getInventory(),
MinecraftClient.getInstance().player.getName()
));
});
});
}
}
public static final Identifier ID = new Identifier(TheClassicofMountainsandOceans.MOD_ID,"opengui");
Identifier用來標示封包,然後使用opengui作為封包的名稱。
PacketByteBuf buf = new PacketByteBuf(Unpooled.buffer());
建立一個PacketByteBuf物件來儲存將要傳送的資料
ServerPlayNetworking.send(player, ID, buf)
使用 ServerPlayNetworking 將封包發送給特定的玩家。player 是目標玩家,ID 是封包的唯一識別碼,buf 是要發送的資料。