tutorial:blockentity_modify_data
This is an old revision of the document!
Table of Contents
Modify BlockEntity data
Introduction
In the previous tutorial, we have created a block entity. Now we try to modify the block entity data. The DemoBlockEntity
class should be written like this:
- DemoBlockEntity.class
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, RegistryWrapper.WrapperLookup registryLookup) { nbt.putInt("number", number); super.writeNbt(nbt, registryLookup); } @Override public void readNbt(NbtCompound nbt, RegistryWrapper.WrapperLookup registryLookup) { super.readNbt(nbt); number = nbt.getInt("number", registryLookup); } }
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, but we just expose the field here for simplicity..
Modifying the data
This gets the BlockEntity
at the right-clicked the block's position and if it's of the type DemoBlockEntity
, increments its number
field and sends a chat message to the player.
- DemoBlock.class
public class DemoBlock extends BlockWithEntity { [...] @Override public ActionResult onUse(BlockState state, World world, BlockPos pos, PlayerEntity player, BlockHitResult hit) { if (!world.isClient){ BlockEntity blockEntity = world.getBlockEntity(pos); if (blockEntity instanceof DemoBlockEntity demoBlockEntity) { demoBlockEntity.number++; player.sendMessage(Text.literal("Number is " + demoBlockEntity.number)); return ActionResult.SUCCESS; } } return ActionResult.PASS; } }
tutorial/blockentity_modify_data.1724630463.txt.gz · Last modified: 2024/08/26 00:01 by solidblock