I have a simple block used as item storage in game, and I've added methods to the block to enable the TileEntity to be broken with a pick and placed elsewhere in the world, preserving the inventory within the storage block.
All works fine, however there is a problem that can cause the inventory of the block to be cleared, the steps to reproduce this are as follows:
1. add item(s) to the inventory of the storage block
2. break the storage block
3. place the storage block back in the world (in a different location)
4. Inventory in the storage block has moved with the block correctly
5. quit the game and re-launch
6. Inventory in the storage block is lost
Mitigating actions:
there are no save issues unless the storage block is moved
if the block is broken and placed in the exact same location, then the inventory seems to persist between saves fine
if the player continues to play for an indeterminate amount of time (i.e. doesn't quit immediately), the inventory of the moved storage block will persist between saves
It's the first time I've tried to have a block with a TileInventory persist after the block is broken using NBT, so I'm sure I'm getting something wrong, though I have used this post to guide me. Any help understand what I'm doing wrong would be appreciated.
Relevant code:
@Override
public void breakBlock(World world, BlockPos blockPos, IBlockState blockState)
{
NBTTagCompound tag = new NBTTagCompound();
TileEntity blockTileEntity = world.getTileEntity(blockPos);
blockTileEntity.writeToNBT(tag);
ItemStack blockItem = new ItemStack(Item.getItemFromBlock(this), 1, this.damageDropped(blockState));
EntityItem entityitem = new EntityItem(world, blockPos.getX(), blockPos.getY(), blockPos.getZ(), blockItem);
entityitem.getEntityItem().setTagCompound(tag);
world.spawnEntityInWorld(entityitem);
}
@Override
public void onBlockPlacedBy(World world, BlockPos pos, IBlockState blockState, EntityLivingBase entityPlayer, ItemStack itemStack)
{
super.onBlockPlacedBy(world, pos, blockState, entityPlayer, itemStack);
TileEntity blockTileEntity = world.getTileEntity(pos);
if (blockTileEntity != null && blockTileEntity instanceof SiloTileEntity)
{
SiloTileEntity siloTileEntity = (SiloTileEntity) blockTileEntity;
if (itemStack.hasTagCompound())
{
NBTTagCompound tag = itemStack.getTagCompound();
siloTileEntity.readFromNBT(tag);
siloTileEntity.markDirty();
}
}
}