Glyceryl
本帖最后由 Glyceryl 于 2022-8-17 17:33 编辑

游戏版本:1.12.2

我打算通过右键一个方块来改变它的状态,并保留它的NBT数据,但是我发现如果直接用setBlockState的话,该方块的NBT就会还原为初始状态(但如果不加将该操作删除,则功能恢复正常,但是无法改变方块状态)。我的部分代码如下:
    //该方法用于更改该方块的状态
    public void setWaterLevel(World world, BlockPos pos, IBlockState state, int level) {
        IBlockState newState = state.withProperty(LEVEL, MathHelper.clamp(level, 0, 3));
        world.setBlockState(pos, newState);
        world.notifyBlockUpdate(pos, state, state, 3);
    }

    @Override
    public boolean onBlockActivated(World world, BlockPos pos, IBlockState state, EntityPlayer player,
                                    EnumHand hand, EnumFacing facing, float f1, float f2, float f3) {
        if (world.isRemote) {
            world.notifyBlockUpdate(pos, state, state, 3);
        }
        //获取玩家手上的物品的值
        ItemStack heldItemStack = player.inventory.getCurrentItem();
        TileEntity tileEntity = world.getTileEntity(pos);
        if (!(tileEntity instanceof EntityBrewingCauldron)) return true;
        EntityBrewingCauldron entityBrewingCauldron = (EntityBrewingCauldron)tileEntity;
        int cauldronMetadata = entityBrewingCauldron.getLiquidData();
        if (heldItemStack.getItem() == Items.WATER_BUCKET) {
            //更改该方块的状态
            setWaterLevel(world, pos, state, 3);
            //fillCauldronWithWaterBucket()方法|会将NBT的值修改为3
            if (entityBrewingCauldron.fillCauldronWithWaterBucket()) {
             ....
            }
            //此处能够输出正常的NBT数据
            System.out.println(entityBrewingCauldron.getLiquidLevel());
            return true;
        }
        //以下是判断是否用正确的物品进行右键
        if (heldItemStack.getItem() == Items.GLASS_BOTTLE) {
            //此处输出的NBT数据为0,正常情况下大于0
            System.out.println(entityBrewingCauldron.getLiquidLevel());
            //如果不为0的时候就执行以下代码
            if (!entityBrewingCauldron.isCauldronEmpty()) {
             ....
            }
        }
         ....
        return true;
    }



youyihj
重写你的 TileEntity 的 shouldRefresh 方法,改成 return oldState.getBlock() != newSate.getBlock();

Glyceryl
youyihj 发表于 2022-8-17 17:11
重写你的 TileEntity 的 shouldRefresh 方法,改成 return oldState.getBlock() != newSate.getBlock(); ...

感谢,问题已经解决了!