0

我正在尝试创建一个基本块实体,该实体具有一个整数变量,每次玩家单击该块时都会增加。我还想将变量的值保存到实体的标记复合中,以便我可以再次加载它。

点击部分工作正常,但保存/加载部分似乎根本不起作用。我实现了 toTag 和 fromTag 方法,但是当我重新进入世界并使用 /data 检查值时,它是 0。我还注意到当我进入世界而不是退出世界时会调用 toTag,这似乎违反直觉我。任何帮助表示赞赏,这是我到目前为止的代码:

主要模组类:

public class MyMod implements ModInitializer{

    @Override
    public void onInitialize() {
        Registry.register(Registry.BLOCK, identifier("my_block"), BlockList.myBlock);
        BlockEntityTypeList.myBlockEntityType = Registry.register(Registry.BLOCK_ENTITY_TYPE, identifier("my_block_entity_type"), 
            BlockEntityType.Builder.create(MyBlockEntityType::new, BlockList.myBlock).build(null));
    }

    public Identifier identifier(String name) {
        return new Identifier(References.modId, name);
    }

}

块类:

public class MyBlock extends Block implements BlockEntityProvider{

    private MyBlockEntity entity;

    public MyBlock() {
        super(Settings.of(Material.WOOD));
    }

    @Override
    public BlockEntity createBlockEntity(BlockView view) {
        entity = new MyBlockEntity();
        return entity;
    }

    @Override
    public ActionResult onUse(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand,
            BlockHitResult hit) {

        entity.increaseCount();
        return ActionResult.SUCCESS;
    }
}

块实体类:

public class MyBlockEntity extends BlockEntity{

    private int count;

    public MyBlockEntity() {
        super(BlockEntityTypeList.myBlockEntityType);   
    }

    public void increaseCount() {
        count += 1;
        markDirty();
    }

    public void decreaseCount() {
        count -= 1;
        markDirty();
    }

    public int getCount() {
        return count;
    }

    @Override
    public CompoundTag toTag(CompoundTag tag) {
        super.toTag(tag);
        System.out.println("saving count");
        tag.putInt("count", count);
        return tag;
    }

    @Override
    public void fromTag(BlockState state, CompoundTag tag) {
        super.fromTag(state, tag);
        System.out.println("loading count");
        count = tag.getInt("count");
    }
}
4

0 回答 0