====== 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 [[tutorial:blocks|Block]] and a [[tutorial:blockentity|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;
}
}