1.16.5模组开发:ClientPlayerEntity无法转为ServerPlayerEntity报错求助
问题原因与解决方案
核心问题
你在客户端逻辑分支里调用了需要服务端玩家实体的NetworkHooks.openGui()方法。worldIn.isClientSide()为true时,当前的player是ClientPlayerEntity,强行转为ServerPlayerEntity必然触发类型转换错误。
NetworkHooks.openGui()是服务端专属方法,必须在服务端环境下调用——它需要处理服务端与客户端的GUI同步逻辑,只能接收ServerPlayerEntity类型的参数。
修复步骤
把代码中的客户端判断改为服务端判断,即将if(worldIn.isClientSide())改成if(!worldIn.isClientSide()),确保只有服务端才执行打开GUI的逻辑:
@SuppressWarnings("deprecation") @Override public ActionResultType use(BlockState p_225533_1_, World worldIn, BlockPos pos, PlayerEntity player, Hand p_225533_5_, BlockRayTraceResult p_225533_6_) { if(!worldIn.isClientSide()) { // 改为服务端判断 TileEntity te = worldIn.getBlockEntity(pos); if(te instanceof DisplayCaseTileEntity) { NetworkHooks.openGui((ServerPlayerEntity) player, (DisplayCaseTileEntity) te, pos); } } return super.use(p_225533_1_, worldIn, pos, player, p_225533_5_, p_225533_6_); }
补充说明
Minecraft采用客户端-服务端双端架构,玩家右键方块的事件会同时在两端触发:
- 客户端分支(
worldIn.isClientSide() == true)适合处理本地视觉/音效反馈,比如播放点击音效、生成粒子效果 - 服务端分支(
worldIn.isClientSide() == false)负责处理数据同步、GUI打开这类需要跨端交互的逻辑
教程作者没遇到问题,大概率是他的代码里判断的是服务端而非客户端,可能是你抄代码时搞反了判断条件。
内容的提问来源于stack exchange,提问作者coriin
相关产品推荐
相关产品推荐

