I've managed to create my TileEntity class for a block I'm working with and I sort of understand the read and write methods I've overridden, but I'd also like to know if there is any way to get information back from the TileEntity on the client side. I want to be able to do something like this:
private final ItemStackHandler itemHandler = createHandler();
private final LazyOptional<IItemHandler> handler = LazyOptional.of(
() -> itemHandler);
private Item contained;
private Item toDrop;
private ItemStackHandler createHandler(){
return new ItemStackHandler(1){
@Override
protected void onContentsChanged(int slot){
markDirty();
}
@Nonnull
@Override
public boolean isItemValid(int slot, @Nonnull ItemStack item){
if(item.getItem() instanceof SwordItem){
return true;
}
return false;
}
@Nonnull
@Override
public ItemStack insertItem(int slot, @Nonnull ItemStack item, boolean simulate){
return super.insertItem(slot,item,simulate);
}
};
}
@Override
public void read(BlockState blockState, CompoundNBT nbt){
super.read(blockState,nbt);
itemHandler.deserializeNBT(nbt.getCompound("contained"));
}
@Override
public CompoundNBT write(CompoundNBT nbt){
CompoundNBT ourNBT = super.write(nbt);
this.toDrop = (Item)ourNBT.get("contained");
ourNBT.put("contained",itemHandler.serializeNBT());
this.contained = ((Item)ourNBT.get("contained"));
return ourNBT;
}
The modded block should basically drop the item it is containing when the player right clicks the block with a new item, then store the new Item. I use an event for this, and my only problem is figuring out how I can call back something stored in the TileEntity.
I know in my code casting the
(Item)ourNBT.get("contained")
CompoundNBT to an Item doesn't work, but this is kind of just laying out my thought process. If anyone could give me some insight into what I'm missing and what I'm doing wrong I'd be super thankful! Also if my entire idea with using events to do this is flawed, then I'd be happy to hear that too haha.