public class ColorBlockEntity extends BlockEntity { public int color = 0x3495eb; public ColorBlockEntity(BlockPos pos, BlockState state) { super(TutorialBlockEntityTypes.COLOR_BLOCK, pos, state); } // 以下两个方块指定了颜色数据的序列化。 @Override protected void readNbt(NbtCompound nbt, RegistryWrapper.WrapperLookup registryLookup) { super.readNbt(nbt, registryLookup); color = nbt.getInt("color"); // 当数据通过“/data”命令修改,或者放置了有“block_entity_data”组件的物品时, // 需要同步更新。 if (world != null) { world.updateListeners(pos, getCachedState(), getCachedState(), 0); } } @Override protected void writeNbt(NbtCompound nbt, RegistryWrapper.WrapperLookup registryLookup) { super.writeNbt(nbt, registryLookup); nbt.putInt("color", color); } @Nullable @Override public Packet toUpdatePacket() { return BlockEntityUpdateS2CPacket.create(this); } @Override public NbtCompound toInitialChunkDataNbt(RegistryWrapper.WrapperLookup registryLookup) { return createNbt(registryLookup); } @Override public @Nullable Object getRenderData() { // 这是来自 `RenderDataBlockEntity` 类的方法。 return color; } }