User Tools

Site Tools


zh_cn:tutorial:blockentity_modify_data

修改方块实体数据

介绍

拥有一个与某个 方块 关联,并持有一些数据的 方块实体 非常棒, 但是如何改变里面的数据?

在继续之前,你将需要一个 方块 和一个 方块实体,这应该与下面代码的形式类似:

public class DemoBlockEntity extends BlockEntity {
 
    public int number = 0;
 
    public DemoBlockEntity(BlockPos pos, BlockState state) {
        super(ExampleMod.DEMO_BLOCK_ENTITY, pos, state);
    }
 
    @Override
    public void writeNbt(NbtCompound nbt) {
        nbt.putInt("number", number);
 
        super.writeNbt(nbt);
    }
 
    @Override
    public void readNbt(NbtCompound nbt) {
        super.readNbt(nbt);
 
        number = nbt.getInt("number");
    }
}

确保 number 的作用域是 public,因为我们将在 DemoBlock 类中改变它的值。你也可以实现 getter 以及 setter 方法。

From Block's onUse()

这将会在右键点击方块的位置获得 方块实体 并且如果它的类型是 DemoBlockEntity,它的 number 属性会增加并且会发送一条消息给玩家。

public class DemoBlock extends Block implements BlockEntityProvider {
 
    [...]
 
    @Override
    public ActionResult onUse(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockHitResult hit) {
        if (!world.isClient){
            BlockEntity blockEntity = world.getBlockEntity(pos);
            if (blockEntity instanceof DemoBlockEntity){
                DemoBlockEntity demoBlockEntity = (DemoBlockEntity) blockEntity;
                demoBlockEntity.number++;
                player.sendMessage(Text.literal("Number is... "+demoBlockEntity.number), false);
 
                return ActionResult.SUCCESS;
            }
        }
 
        return ActionResult.PASS;
    }
}
zh_cn/tutorial/blockentity_modify_data.txt · Last modified: 2024/05/30 08:21 by sjk1949