User Tools

Site Tools


tutorial:blockentity_modify_data

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
tutorial:blockentity_modify_data [2023/06/18 13:24] – removed - external edit (Unknown date) 127.0.0.1tutorial:blockentity_modify_data [2023/06/18 13:24] (current) – ↷ Page moved and renamed from block_modifying_blockentity to tutorial:blockentity_modify_data terra
Line 1: Line 1:
 +====== 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:
 +
 +<code java>
 +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");
 +    }
 +}
 +</code>
 +
 +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.
 +
 +<code java>
 +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;
 +    }
 +}
 +</code>