Jump to content

[SOLVED!][1.10.2] Items in slot won't save to NBT?


Macintoshuser_2

Recommended Posts

Hello, I am having a bit of trouble with the Tile Entity for my RF Generator for my mod, Mac's Utilities Remastered. The problem that I am having is that when I put a stack of Items into a slot in the GUI, close the GUI, exit the world, and then rejoin the world, the Items that were in the slot were not saved to NBT. How do I fix this?

 

TileEntityRFGenerator.java:

 

package com.macintoshuser2.macsutilities.tileentities;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.text.ITextComponent
import net.minecraft.util.text.TextComponentString;
import net.minecraft.util.text.TextComponentTranslation;

public class TileEntityRFGenerator extends TileEntity implements IInventory {
   
   private ItemStack[] inventory;
   private String customName;

   public TileEntityRFGenerator() {
      this.inventory = new ItemStack[this.getSizeInventory()];
   }

   public void setCustomName(String customName) {
      this.customName = customName;
   }

   public String getCustomName() {
      return customName;
   }
   
   @Override
   public String getName() {
      return this.hasCustomName() ? this.customName : "container.rfGenerator";
   }

   @Override
   public boolean hasCustomName() {
      return this.customName != null && !this.customName.equals("");
   }

   @Override
   public ITextComponent getDisplayName() {
      return this.hasCustomName() ? new TextComponentString(this.getName()) : new TextComponentTranslation(this.getName());
   }

   @Override
   public int getSizeInventory() {
      return 1;
   }
   
   @Override
   public ItemStack getStackInSlot(int index) {
      if(index < 0 || index >= this.getSizeInventory()) {
         return null;
      }
      return this.inventory[index];
   }

   @Override
   public ItemStack decrStackSize(int index, int count) {
      if(this.getStackInSlot(index) != null) {
         itemstack = this.getStackInSlot(index);
         this.setInventorySlotContents(index, null);
         this.markDirty();
         return itemstack;
      } else {
         itemstack = this.getStackInSlot(index).splitStack(count);
         if(this.getTackInSlot(index).stackSize <= 0) {
            this.setInventorySlotContents(index, null);
         } else {
            this.setInventorySlotContents(index, this.getStackInSlot(index));
         }

         this.markDirty();
         return itemstack;
      }
   } else {
      return null;
   }

   @Override
   public void setInventorySlotContents(int index, ItemStack stack) {
      if(index < 0 || index >= this.getSizeInventory()) {
         return;
      }
   
      if(stack != null && stack.stackSize > this.getInventoryStackLimit()) {
         stack.stackSize = this.getInventoryStackLimit();
      }

      if(stack != null && stack.stackSize == 0) {
         stack = null;
      }
      
      this.inventory[index] = stack;
      this.markDirty();
   }

   @Override
   public ItemStack removeStackFromSlot(int index) {
      ItemStack stack = this.getStackInSlot(index);
      this.setInventorySlotContents(index, null);
      return stack;
   }

   @Override
   public int getInventoryStackLimit() {
      return 64;
   }

   @Override
   public boolean isUseableByPlayer(EntityPlayer player) {
      return this.worldObj.getTileEntity(this.getPos()) == this && player.getDistanceSq(this.pos.add(0.5, 0.5, 0.5)) <= 64
   }

   @Override
   public boolean isItemValidForSlot(int index, ItemStack stack) {
      return stack.getItem() == Items.REDSTONE || stack.getItem() == Item.getItemFromBlock(Blocks.REDSTONE_BLOCK) ? true : false;
   }

   @Override
   public int getField(int id) {
      return 0;
   }

   @Override
   public void setField(int id, int value) {
   }

   @Override
   public int getFieldCount() {
      return 0;
   }

   @Override
   public void clear() {
      for(int i = 0; i < this.getSizeInventory(); i++) {
         this.setInventorySlotContents(i, null);
      }
   }

   @Override
   public NBTTagCompound writeToNBT(NBTTagCompound nbt) {
      super.writeToNBT(nbt);

      NBTTagList list = new NBTTagList();
      for(int i = 0; i < this.getSizeInventory(); ++i) {
         if(this.getStackInSlot(i) != null) {
            NBTTagCompound stackTag = new NBTTagCompound();
            stackTag.setByte("Slot", (byte) i);
            this.getStackInSlot(i).writeToNBT(stackTag);
            list.appendTag(stackTag);
         }
      }
      nbt.setTag("Items", list);

      if(this.hasCustomName()) {
         nbt.setString("CustomName", this.getCustomName());
      }
      return nbt;
   }

   @Override
   public void redFromNBT(NBTTagCompound nbt) {
      super.readFromNBT(nbt);
      
      NBTTagList list = nbt.getTagList("Items", 10);
      for(int i = 0; i < list.tagCount(); ++i) {
         NBTTagCompound stackTag = list.getCompoundTagAt(i);
         int slot = stackTag.getByte("Slot") & 255;
         this.setInventorySlotContents(slot, ItemStack.loadItemStackFromNBT(stackTag));
      }
      
      if(nbt.hasKey("CustomName", ) {
            this.setCustomName(nbt.getString("CustomName"));
      }
   }
   
   @Override
   public void openInventory(EntityPlayer player) {
   }

   @Override
   public void closeInventory(EntityPlayer player) {
   }
}

 

 

How do I fix it?

Link to comment
Share on other sites

Don't use IInventory, use Capabilities.

Namely the ItemStackHandler capability.

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Link to comment
Share on other sites

How would I go about changing my container accordingly upon making that change?

Instead of new Slot do new SlotItemHandler

VANILLA MINECRAFT CLASSES ARE THE BEST RESOURCES WHEN MODDING

I will be posting 1.15.2 modding tutorials on this channel. If you want to be notified of it do the normal YouTube stuff like subscribing, ect.

Forge and vanilla BlockState generator.

Link to comment
Share on other sites

I made the changes to the container and now I can't open the GUI and the block won't drop items upon being broken.

 

ContainerRFGenerator.java:

 

package com.macintoshuser2.macsutilities.container;

import com.macintoshuser2.macsutilities.tileentities.TileEntityRFGenerator;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
import net.minecraftforge.items.IItemHandler;
import net.minecraftforge.items.SlotItemHandler;

public class ContainerRFGenerator extends Container {

private TileEntityRFGenerator rfGen;

public ContainerRFGenerator(IInventory playerInventory, TileEntityRFGenerator rfGen) {
	this.rfGen = rfGen;

	this.addSlotToContainer(new SlotItemHandler((IItemHandler) rfGen, 0, 30, 35));

	for(int y = 0; y < 3; ++y) {
		for(int x = 0; x < 9; ++x) {
			this.addSlotToContainer(new Slot(playerInventory, x + y * 9 + 9, 8 + x * 18, 84 + y * 18));
		}
	}

	for(int x = 0; x <9; ++x) {
		this.addSlotToContainer(new Slot(playerInventory, x, 8 + x * 18, 142));
	}
}

@Override
public boolean canInteractWith(EntityPlayer playerIn) {
	return true;
	//return this.rfGen.isUseableByPlayer(playerIn);
}

@Override
public ItemStack transferStackInSlot(EntityPlayer playerIn, int fromSlot) {
	ItemStack previous = null;
	Slot slot = (Slot) this.inventorySlots.get(fromSlot);

	if(slot != null && slot.getHasStack()) {
		ItemStack current = slot.getStack();
		previous = current.copy();

		if(fromSlot < 1) {
			if(!this.mergeItemStack(current,  1,  this.inventorySlots.size(), true)) {
				return null;
			}
		} else {
			if(!this.mergeItemStack(current, 0, 1, false)) {
				return null;
			}
		}

		if(current.stackSize == 0) {
			slot.putStack((ItemStack) null);
		} else {
			slot.onSlotChanged();
		}
	}
	return previous;
}
}

 

 

TileEntityRFGenerator.java:

 

package com.macintoshuser2.macsutilities.tileentities;

import javax.annotation.Nullable;

import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.items.CapabilityItemHandler;
import net.minecraftforge.items.ItemStackHandler;

public class TileEntityRFGenerator extends TileEntity {
private ItemStackHandler inventory = new ItemStackHandler(1);

@Override
public NBTTagCompound writeToNBT(NBTTagCompound compound) {
	compound.setTag("inventory", inventory.serializeNBT());
	return super.writeToNBT(compound);
}

@Override
public void readFromNBT(NBTTagCompound compound) {
	inventory.deserializeNBT(compound.getCompoundTag("inventory"));
	super.readFromNBT(compound);
}

@Override
public boolean hasCapability(Capability<?> capability, EnumFacing facing) {
	return capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY || super.hasCapability(capability, facing);
}

@Nullable
@Override
public <T> T getCapability(Capability<T> capability, EnumFacing facing) {
	return capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY ? (T)inventory : super.getCapability(capability, facing);
}
}

 

BlockRFGenerator.java:

 

package com.macintoshuser2.macsutilities.blocks;

import java.util.List;

import org.lwjgl.input.Keyboard;

import com.macintoshuser2.macsutilities.MacsUtilities;
import com.macintoshuser2.macsutilities.client.gui.MacGuiHandler;
import com.macintoshuser2.macsutilities.tileentities.TileEntityRFGenerator;

import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.Entity;
import net.minecraft.entity.boss.EntityDragon;
import net.minecraft.entity.boss.EntityWither;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumBlockRenderType;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.TextFormatting;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.items.CapabilityItemHandler;
import net.minecraftforge.items.IItemHandler;

public class BlockRFGenerator extends BlockContainer {
public BlockRFGenerator() {
	super(Material.IRON);

	this.setUnlocalizedName("rf_generator");
	this.setRegistryName("rf_generator");
}

@Override
public void breakBlock(World world, BlockPos pos, IBlockState blockstate) {
    TileEntityRFGenerator rfGen = new TileEntityRFGenerator();
    
    IItemHandler itemHandler = rfGen.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, EnumFacing.NORTH);
    ItemStack stack = itemHandler.getStackInSlot(0);
    if(stack != null) {
    	EntityItem item = new EntityItem(world, pos.getX(), pos.getY(), pos.getZ(), stack);
    	world.spawnEntityInWorld(item);
    }
    
    super.breakBlock(world, pos, blockstate);
}

@Override
public boolean isFullBlock(IBlockState state) {
	return true;
}

@Override
public boolean isOpaqueCube(IBlockState state) {
	return false;
}

@Override
public void addInformation(ItemStack stack, EntityPlayer player, List<String> tooltip, boolean advanced) {
	tooltip.add(TextFormatting.BOLD + "<HOLD LEFT SHIFT FOR MORE INFO>");
	if(Keyboard.isKeyDown(Keyboard.KEY_LSHIFT)) {
		tooltip.remove(1);
		tooltip.add(TextFormatting.RED + "Redstone Dust = 50 RF/t");
		tooltip.add(TextFormatting.RED + "Redstone Block = 450 RF/t");
	}
}

@Override
public boolean canEntityDestroy(IBlockState state, IBlockAccess world, BlockPos pos, Entity entity) {
	return entity instanceof EntityWither || entity instanceof EntityDragon ? false : true;
}

@Override
public TileEntity createNewTileEntity(World worldIn, int meta) {
	return new TileEntityRFGenerator();
}

@Override
public EnumBlockRenderType getRenderType(IBlockState state) {
	return EnumBlockRenderType.MODEL;
}

@Override
public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumHand hand, ItemStack heldItem, EnumFacing side, float hitX, float hitY, float hitZ) {
	if(!worldIn.isRemote) {
		playerIn.openGui(MacsUtilities.instanceOfMacUtil, MacGuiHandler.RF_GENERATOR_IDENTIFIER, worldIn, pos.getX(), pos.getY(), pos.getZ());
	}
	return true;
}
}

Link to comment
Share on other sites

You need to change your container and guicontainer as well.

 

Instead of taking an IInventory, take in your TE.  Then for slots, instead of

new Slot

you want

new SlotItemHandler

.

 

e.g.

https://github.com/Draco18s/ReasonableRealism/blob/master/src/main/java/com/draco18s/ores/inventory/ContainerSifter.java

 

(SlotDust is a custom slot class that extends SlotItemHandler)

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Link to comment
Share on other sites

Ok, I made the changes and the gui will now open. I am however still having trouble with the NBT. The Items in the slot will not save to NBT when I log out of the world and will not read it when I get back into the world.  I am also still having the issue of Items not dropping when I break the block.

 

I put the code on github that way it'd just make it a whole lot easier.

 

BlockRFGenerator.java: https://github.com/Macintoshuser2/MacsUtilitiesRemastered/blob/master/src/main/java/com/macintoshuser2/macsutilities/blocks/BlockRFGenerator.java

 

ContainerRFGenerator.java: https://github.com/Macintoshuser2/MacsUtilitiesRemastered/blob/master/src/main/java/com/macintoshuser2/macsutilities/container/ContainerRFGenerator.java

 

TileEntityRFGenerator.java: https://github.com/Macintoshuser2/MacsUtilitiesRemastered/blob/master/src/main/java/com/macintoshuser2/macsutilities/tileentities/TileEntityRFGenerator.java

 

GuiRFGenerator.java: https://github.com/Macintoshuser2/MacsUtilitiesRemastered/blob/master/src/main/java/com/macintoshuser2/macsutilities/client/gui/GuiRFGenerator.java

 

Link to comment
Share on other sites

Guest
This topic is now closed to further replies.

Announcements



×
×
  • Create New...

Important Information

By using this site, you agree to our Terms of Use.