User Tools

Site Tools


tutorial:blockentity_modify_data

Modify BlockEntity data

Introduction

Having a BlockEntity, which holds some data, connected to a Block is nice, but how to change the data?

Before proceeding, you will need a Block and a BlockEntity, which should look similar to this:

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");
    }
}

Make sure the number field is public, as we are going to change it in the DemoBlock class. You could also make getter and setter methods.

From Block's onUse()

This gets the BlockEntity at the right-clicked Block's position and if it's of the type DemoBlockEntity, increments its number field and sends a chat message to the player.

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;
    }
}
tutorial/blockentity_modify_data.txt · Last modified: 2023/06/18 13:24 by terra