Posted August 3, 20205 yr It's first time using capability & packet system, so I think make a stupid mistake. Please tell me where I'm wrong? I want to sync float value in my capability with client. PacketHandler: public class PacketHandler { private static final String PROTOCOL_VERSION = "1.0"; public static final SimpleChannel CHANNEL = NetworkRegistry.ChannelBuilder .named(new ResourceLocation(DietMod.MODID, "main_channel")) .clientAcceptedVersions(PROTOCOL_VERSION::equals) .serverAcceptedVersions(PROTOCOL_VERSION::equals) .networkProtocolVersion(() -> PROTOCOL_VERSION) .simpleChannel(); public static void register() { CHANNEL.registerMessage(0, CapabilityPacket.class, CapabilityPacket::encode, CapabilityPacket::decode, CapabilityPacket::handle); } public static void sendTo(Object message, PlayerEntity player) { CHANNEL.send(PacketDistributor.PLAYER.with(() -> (ServerPlayerEntity) player), message); } } Packet: public class CapabilityPacket { private final float scale; public CapabilityPacket(float scale) { this.scale = scale; } public static void encode(CapabilityPacket pkt, PacketBuffer buf) { buf.writeFloat(pkt.scale); } public static CapabilityPacket decode(PacketBuffer buf) { return new CapabilityPacket(buf.readFloat()); } public static void handle(CapabilityPacket pkt, Supplier<NetworkEvent.Context> contextSupplier) { NetworkEvent.Context context = contextSupplier.get(); context.enqueueWork(() -> { PlayerEntity player = context.getSender(); if (player == null) return; player.getCapability(ScaleProvider.SCALE_CAPABILITY).orElseThrow(() -> new IllegalArgumentException()).setScale(pkt.scale); <-- I think this is wrong. }); context.setPacketHandled(true); } } Main: public TestMod() { PacketHandler.register(); } @SubscribeEvent public static void syncCap(TickEvent.PlayerTickEvent event) { if (!event.player.world.isRemote()) { float scale = event.player.getCapability(ScaleProvider.SCALE_CAP).orElseThrow(() -> new IllegalArgumentException()).getScale(); PacketHandler.sendTo(new CapabilityPacket(scale), event.player); } } Edited August 3, 20205 yr by kyazuki
August 3, 20205 yr Don't send the packet each tick, send it when changes were made or when needed. context.getSender() gives a ServerPlayerEntity, use Minecraft.getInstance().player to get the client player
August 3, 20205 yr Actually, if you really need to send entire capability with network package, you may write your capability into CompoundNBT tag and then write this tag into PacketBuffer. But as poopoodice said, avoid excess synchronization. Everything said above may be absolutely wrong. No rights reserved.
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.