File size: 2,797 Bytes
d517dc9
 
 
 
1
2
3
4
5
{"type": "session", "harness": "opencode", "id": "mc-0038", "name": "Block Entities"}
{"type": "message", "message": {"role": "system", "content": "You are an expert Fabric mod developer. You write idiomatic Minecraft Fabric mods using Java, Fabric API, and Yarn mappings."}}
{"type": "message", "message": {"role": "user", "content": "How do I create a block entity that saves and loads NBT data and ticks?"}}
{"type": "message", "message": {"role": "assistant", "content": "```java\npackage com.example.mymod;\n\nimport net.minecraft.block.BlockState;\nimport net.minecraft.block.entity.BlockEntity;\nimport net.minecraft.nbt.NbtCompound;\nimport net.minecraft.util.math.BlockPos;\n\npublic class CustomBlockEntity extends BlockEntity {\n    private int energy = 0;\n    private String customName = \"\";\n    private boolean isProcessing = false;\n\n    public CustomBlockEntity(BlockPos pos, BlockState state) {\n        super(MyBlockEntities.CUSTOM, pos, state);\n    }\n\n    @Override\n    protected void writeNbt(NbtCompound nbt) {\n        super.writeNbt(nbt);\n        nbt.putInt(\"Energy\", energy);\n        nbt.putString(\"CustomName\", customName);\n        nbt.putBoolean(\"IsProcessing\", isProcessing);\n    }\n\n    @Override\n    public void readNbt(NbtCompound nbt) {\n        super.readNbt(nbt);\n        energy = nbt.getInt(\"Energy\");\n        customName = nbt.getString(\"CustomName\");\n        isProcessing = nbt.getBoolean(\"IsProcessing\");\n    }\n\n    public void syncData() {\n        if (world != null && !world.isClient) {\n            world.updateListeners(pos, getCachedState(), getCachedState(), 3);\n        }\n    }\n\n    public void tick() {\n        if (isProcessing && energy > 0) {\n            energy--;\n            syncData();\n        }\n    }\n}\n```\n\nRegister the block entity:\n```java\npublic class MyBlockEntities {\n    public static final BlockEntityType<CustomBlockEntity> CUSTOM = \n        BlockEntityType.Builder.create(CustomBlockEntity::new, MyBlocks.SIMPLE_BLOCK).build();\n\n    public static void registerBlockEntities() {\n        Registry.register(Registries.BLOCK_ENTITY_TYPE, MyMod.id(\"custom\"), CUSTOM);\n    }\n}\n```\n\nAdd ticking in block class:\n```java\npublic class CustomBlock extends Block implements BlockEntityProvider {\n    @Override\n    public BlockEntity createBlockEntity(BlockPos pos, BlockState state) {\n        return new CustomBlockEntity(pos, state);\n    }\n\n    @Override\n    public BlockEntityTicker getTicker(World world, BlockState state, BlockEntityType type) {\n        if (!world.isClient) {\n            return (world1, pos, state1, be) -> {\n                if (be instanceof CustomBlockEntity custom) custom.tick();\n            };\n        }\n        return null;\n    }\n}\n```"}}