Jump to content

[1.7.10][Solved] Chest doesn't have items until reloading world


Angelo1275902

Recommended Posts

Hello,

 

I am making a mod and what I am trying to do is when my chest is added to the world, it will spawn with an item inside the chest. Right now I have a problem where whenever my custom chest is placed in the world, the items aren't in the chest, unless I reload the world. Here is both my BlockLockedChest file and TileEntityLockedChest file. Some of the code is a bit messy so...  :P

 

BlockLockedChest.java

package com.angelo.venturemod.blocks;

import static net.minecraftforge.common.util.ForgeDirection.DOWN;

import java.util.Iterator;
import java.util.Random;

import net.minecraft.block.Block;
import net.minecraft.block.BlockChest;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.passive.EntityOcelot;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.InventoryLargeChest;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.tileentity.TileEntityChest;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.ChatComponentTranslation;
import net.minecraft.util.MathHelper;
import net.minecraft.world.World;
import net.minecraftforge.common.ChestGenHooks;

import com.angelo.venturemod.VentureMod;
import com.angelo.venturemod.items.Items;
import com.angelo.venturemod.tileentities.TileEntityLockedChest;

import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;

public class BlockLockedChest extends BlockChest{

private final Random field_149955_b = new Random();

TileEntityLockedChest telockedchest;
//IInventory iinventory;

protected BlockLockedChest(int par1) {
	super(par1);
	this.setBlockName("Locked Chest");

	this.setBlockTextureName(VentureMod.MODID+":Locked Chest");
	this.setBlockUnbreakable();
	this.setCreativeTab(VentureMod.ventureBlocksTab);


}

@Override
public boolean canHarvestBlock(EntityPlayer player, int meta){
	return false;
}

@Override 
    public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer ep, int side, float offsetX, float offsetY, float offsetZ){

	if(!world.isRemote){
		//iinventory = this.func_149951_m(world, x, y, z);
		telockedchest = (TileEntityLockedChest)world.getTileEntity(x, y, z);
		if(ep.getHeldItem() != null){	

			if(ep.getHeldItem().getItem() == Items.key){			

				if(telockedchest != null){

					ep.displayGUIChest(telockedchest);
					ep.inventory.consumeInventoryItem(Items.key);
					telockedchest.markDirty();
				}			
			}
			else{
			ep.addChatMessage(new ChatComponentTranslation("You need to use a key to open this chest."));
			}
		}	
		else{
			ep.addChatMessage(new ChatComponentTranslation("You cannot use your hands to open this chest."));
		}
	}
	else{
		return true;
	}
	return false;
}



@Override
public void onBlockAdded(World world, int x, int y, int z){
	super.onBlockAdded(world, x, y, z);
        this.func_149954_e(world, x, y, z);
        Block block = world.getBlock(x, y, z - 1);
        Block block1 = world.getBlock(x, y, z + 1);
        Block block2 = world.getBlock(x - 1, y, z);
        Block block3 = world.getBlock(x + 1, y, z);

        if (block == this)
        {
            this.func_149954_e(world, x, y, z - 1);
        }

        if (block1 == this)
        {
            this.func_149954_e(world, x, y, z + 1);
        }

        if (block2 == this)
        {
            this.func_149954_e(world, x - 1, y, z);
        }

        if (block3 == this)
        {
            this.func_149954_e(world, x + 1, y, z);
        }

        telockedchest = (TileEntityLockedChest)world.getTileEntity(x, y, z);
        
	int i;
	int j;

	Random rand = new Random();

	telockedchest.setInventorySlotContents(i = rand.nextInt(27), Items.getRandomItem());

	j = rand.nextInt(27);
	while(j == i){
		j = rand.nextInt(27);
	}

	telockedchest.setInventorySlotContents(j, Items.getRandomItem());

	telockedchest.markDirty();

         
}



@Override
public TileEntity createNewTileEntity(World p_149915_1_, int p_149915_2_)
    {
        TileEntityLockedChest tileentitylockedchest = new TileEntityLockedChest();
        
        return tileentitylockedchest;
    }

/**
* Called when the block is placed in the world.
*/
public void onBlockPlacedBy(World p_149689_1_, int p_149689_2_, int p_149689_3_, int p_149689_4_, EntityLivingBase p_149689_5_, ItemStack p_149689_6_)
{

Block block = p_149689_1_.getBlock(p_149689_2_, p_149689_3_, p_149689_4_ - 1);
Block block1 = p_149689_1_.getBlock(p_149689_2_, p_149689_3_, p_149689_4_ + 1);
Block block2 = p_149689_1_.getBlock(p_149689_2_ - 1, p_149689_3_, p_149689_4_);
Block block3 = p_149689_1_.getBlock(p_149689_2_ + 1, p_149689_3_, p_149689_4_);
byte b0 = 0;
int l = MathHelper.floor_double((double)(p_149689_5_.rotationYaw * 4.0F / 360.0F) + 0.5D) & 3;
if (l == 0)
{
b0 = 2;
}
if (l == 1)
{
b0 = 5;
}
if (l == 2)
{
b0 = 3;
}
if (l == 3)
{
b0 = 4;
}
if (block != this && block1 != this && block2 != this && block3 != this)
{
p_149689_1_.setBlockMetadataWithNotify(p_149689_2_, p_149689_3_, p_149689_4_, b0, 3);
}
else
{
if ((block == this || block1 == this) && (b0 == 4 || b0 == 5))
{
if (block == this)
{
p_149689_1_.setBlockMetadataWithNotify(p_149689_2_, p_149689_3_, p_149689_4_ - 1, b0, 3);
}
else
{
p_149689_1_.setBlockMetadataWithNotify(p_149689_2_, p_149689_3_, p_149689_4_ + 1, b0, 3);
}
p_149689_1_.setBlockMetadataWithNotify(p_149689_2_, p_149689_3_, p_149689_4_, b0, 3);
}
if ((block2 == this || block3 == this) && (b0 == 2 || b0 == 3))
{
if (block2 == this)
{
p_149689_1_.setBlockMetadataWithNotify(p_149689_2_ - 1, p_149689_3_, p_149689_4_, b0, 3);
}
else
{
p_149689_1_.setBlockMetadataWithNotify(p_149689_2_ + 1, p_149689_3_, p_149689_4_, b0, 3);
}
p_149689_1_.setBlockMetadataWithNotify(p_149689_2_, p_149689_3_, p_149689_4_, b0, 3);
}
}
if (p_149689_6_.hasDisplayName())
{
((TileEntityLockedChest)p_149689_1_.getTileEntity(p_149689_2_, p_149689_3_, p_149689_4_)).func_145976_a(p_149689_6_.getDisplayName());
}

}
/**
     * Lets the block know when one of its neighbor changes. Doesn't know which neighbor changed (coordinates passed are
     * their own) Args: x, y, z, neighbor Block
     */
    public void onNeighborBlockChange(World p_149695_1_, int p_149695_2_, int p_149695_3_, int p_149695_4_, Block p_149695_5_)
    {
        super.onNeighborBlockChange(p_149695_1_, p_149695_2_, p_149695_3_, p_149695_4_, p_149695_5_);
        TileEntityLockedChest tileentitychest = (TileEntityLockedChest)p_149695_1_.getTileEntity(p_149695_2_, p_149695_3_, p_149695_4_);

        if (tileentitychest != null)
        {
            tileentitychest.updateContainingBlockInfo();
        }
    }
public void breakBlock(World p_149749_1_, int p_149749_2_, int p_149749_3_, int p_149749_4_, Block p_149749_5_, int p_149749_6_)
{
	TileEntityLockedChest tileentitychest = (TileEntityLockedChest)p_149749_1_.getTileEntity(p_149749_2_, p_149749_3_, p_149749_4_);
	if (tileentitychest != null)
	{
		for (int i1 = 0; i1 < tileentitychest.getSizeInventory(); ++i1)
		{
			ItemStack itemstack = tileentitychest.getStackInSlot(i1);
			if (itemstack != null)
			{
				float f = this.field_149955_b.nextFloat() * 0.8F + 0.1F;
				float f1 = this.field_149955_b.nextFloat() * 0.8F + 0.1F;
				EntityItem entityitem;
				for (float f2 = this.field_149955_b.nextFloat() * 0.8F + 0.1F; itemstack.stackSize > 0; p_149749_1_.spawnEntityInWorld(entityitem))
				{
					int j1 = this.field_149955_b.nextInt(21) + 10;
					if (j1 > itemstack.stackSize)
					{
						j1 = itemstack.stackSize;
					}
					itemstack.stackSize -= j1;
					entityitem = new EntityItem(p_149749_1_, (double)((float)p_149749_2_ + f), (double)((float)p_149749_3_ + f1), (double)((float)p_149749_4_ + f2), new ItemStack(itemstack.getItem(), j1, itemstack.getItemDamage()));
					float f3 = 0.05F;
					entityitem.motionX = (double)((float)this.field_149955_b.nextGaussian() * f3);
					entityitem.motionY = (double)((float)this.field_149955_b.nextGaussian() * f3 + 0.2F);
					entityitem.motionZ = (double)((float)this.field_149955_b.nextGaussian() * f3);
					if (itemstack.hasTagCompound())
					{
						entityitem.getEntityItem().setTagCompound((NBTTagCompound)itemstack.getTagCompound().copy());
					}
				}
			}
		}
		p_149749_1_.func_147453_f(p_149749_2_, p_149749_3_, p_149749_4_, p_149749_5_);
}
super.breakBlock(p_149749_1_, p_149749_2_, p_149749_3_, p_149749_4_, p_149749_5_, p_149749_6_);
}


private static boolean func_149953_o(World p_149953_0_, int p_149953_1_, int p_149953_2_, int p_149953_3_)
{

	return false;
}

@SideOnly(Side.CLIENT)
public void registerBlockIcons(IIconRegister p_149651_1_)
{
this.blockIcon = p_149651_1_.registerIcon(VentureMod.MODID + ":Locked Chest");
}

/**
     * Checks to see if its valid to put this block at the specified coordinates. Args: world, x, y, z
     */
    public boolean canPlaceBlockAt(World p_149742_1_, int p_149742_2_, int p_149742_3_, int p_149742_4_)
    {
        int l = 0;

        if (p_149742_1_.getBlock(p_149742_2_ - 1, p_149742_3_, p_149742_4_) == this || p_149742_1_.getBlock(p_149742_2_ - 1, p_149742_3_, p_149742_4_) == Blocks.chest)
        {
            ++l;
            return false;
        }

        if (p_149742_1_.getBlock(p_149742_2_ + 1, p_149742_3_, p_149742_4_) == this || p_149742_1_.getBlock(p_149742_2_ + 1, p_149742_3_, p_149742_4_) == Blocks.chest)
        {
            ++l;
            return false;
        }

        if (p_149742_1_.getBlock(p_149742_2_, p_149742_3_, p_149742_4_ - 1) == this || p_149742_1_.getBlock(p_149742_2_, p_149742_3_, p_149742_4_ -1) == Blocks.chest)
        {
            ++l;
            return false;
        }

        if (p_149742_1_.getBlock(p_149742_2_, p_149742_3_, p_149742_4_ + 1) == this || p_149742_1_.getBlock(p_149742_2_, p_149742_3_, p_149742_4_ + 1) == Blocks.chest)
        {
            ++l;
            return false;
        }

        return true;
    }
}

 

TileEntityLockedChest.java

package com.angelo.venturemod.tileentities;

import java.util.Iterator;
import java.util.List;

import com.angelo.venturemod.blocks.BlockLockedChest;

import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.block.Block;
import net.minecraft.block.BlockChest;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.inventory.ContainerChest;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.InventoryLargeChest;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.tileentity.TileEntityChest;
import net.minecraft.util.AxisAlignedBB;

public class TileEntityLockedChest extends TileEntityChest{


private ItemStack[] chestContents = new ItemStack[36];
    
    /** Contains the chest tile located adjacent to this one (if any) */
    public TileEntityLockedChest adjacentChestZNeg;
    /** Contains the chest tile located adjacent to this one (if any) */
    public TileEntityLockedChest adjacentChestXPos;
    /** Contains the chest tile located adjacent to this one (if any) */
    public TileEntityLockedChest adjacentChestXNeg;
    /** Contains the chest tile located adjacent to this one (if any) */
    public TileEntityLockedChest adjacentChestZPos;
    
    private int cachedChestType;
    private String customName;
    
    @Override
public ItemStack decrStackSize(int p_70298_1_, int p_70298_2_) {

    	if (this.chestContents[p_70298_1_] != null)
        {
            ItemStack itemstack;

            if (this.chestContents[p_70298_1_].stackSize <= p_70298_2_)
            {
                itemstack = this.chestContents[p_70298_1_];
                this.chestContents[p_70298_1_] = null;
                markDirty();
                return itemstack;
            }
            else
            {
                itemstack = this.chestContents[p_70298_1_].splitStack(p_70298_2_);

                if (this.chestContents[p_70298_1_].stackSize == 0)
                {
                    this.chestContents[p_70298_1_] = null;
                }

                markDirty();
                return itemstack;
            }
        }
        else
        {
            return null;
        }
}
    @Override
    public void markDirty()
    {
       super.markDirty();
       
    } 
    /**
     * Returns the name of the inventory
     */
    @Override
    public String getInventoryName()
    {
        return this.hasCustomInventoryName() ? this.customName : "Locked Chest";
    }
    
    @Override
    public void setInventorySlotContents(int i, ItemStack itemstack)
    {
    	chestContents[i] = itemstack;
    	if (itemstack != null && itemstack.stackSize > getInventoryStackLimit())
    	{
    		itemstack.stackSize = getInventoryStackLimit();
    	}
    	markDirty();
    }
    
    @Override
    public void readFromNBT(NBTTagCompound p_145839_1_)
    {
    	super.readFromNBT(p_145839_1_);
    	NBTTagList nbttaglist = p_145839_1_.getTagList("Items", 10);
    	this.chestContents = new ItemStack[this.getSizeInventory()];
    	if (p_145839_1_.hasKey("Locked Chest", )
    	{
    		this.customName = p_145839_1_.getString("Locked Chest");
    	}
    	for (int i = 0; i < nbttaglist.tagCount(); ++i)
    	{
    		NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i);
    		int j = nbttagcompound1.getByte("Slot") & 255;
    		if (j >= 0 && j < this.chestContents.length)
    		{
    			this.chestContents[j] = ItemStack.loadItemStackFromNBT(nbttagcompound1);
    		}
    	}
    }
    @Override
    public void writeToNBT(NBTTagCompound p_145841_1_)
    {
        super.writeToNBT(p_145841_1_);
        NBTTagList nbttaglist = new NBTTagList();

        for (int i = 0; i < this.chestContents.length; ++i)
        {
            if (this.chestContents[i] != null)
            {
                NBTTagCompound nbttagcompound1 = new NBTTagCompound();
                nbttagcompound1.setByte("Slot", (byte)i);
                this.chestContents[i].writeToNBT(nbttagcompound1);
                nbttaglist.appendTag(nbttagcompound1);
                
            }
        }

        p_145841_1_.setTag("Items", nbttaglist);

        if (this.hasCustomInventoryName())
        {
            p_145841_1_.setString("Locked Chest", this.customName);
        }
        
    }

    private void func_145978_a(TileEntityLockedChest p_145978_1_, int p_145978_2_){
    if (p_145978_1_.isInvalid())
    {
        this.adjacentChestChecked = false;
    }
    else if (this.adjacentChestChecked)
    {
        switch (p_145978_2_)
        {
            case 0:
                if (this.adjacentChestZPos != p_145978_1_)
                {
                    this.adjacentChestChecked = false;
                }

                break;
            case 1:
                if (this.adjacentChestXNeg != p_145978_1_)
                {
                    this.adjacentChestChecked = false;
                }

                break;
            case 2:
                if (this.adjacentChestZNeg != p_145978_1_)
                {
                    this.adjacentChestChecked = false;
                }

                break;
            case 3:
                if (this.adjacentChestXPos != p_145978_1_)
                {
                    this.adjacentChestChecked = false;
                }
        }
    }
    }
    
    /**
    * Performs the check for adjacent chests to determine if this chest is double or not.
    */
    @Override
    public void checkForAdjacentChests()
    {
    	if (!this.adjacentChestChecked)
    	{
    		this.adjacentChestChecked = true;
    		this.adjacentChestZNeg = null;
    		this.adjacentChestXPos = null;
    		this.adjacentChestXNeg = null;
    		this.adjacentChestZPos = null;
    		if (this.func_145977_a(this.xCoord - 1, this.yCoord, this.zCoord))
    		{
    			this.adjacentChestXNeg = (TileEntityLockedChest)this.worldObj.getTileEntity(this.xCoord - 1, this.yCoord, this.zCoord);
    		}
    		if (this.func_145977_a(this.xCoord + 1, this.yCoord, this.zCoord))
    		{
    			this.adjacentChestXPos = (TileEntityLockedChest)this.worldObj.getTileEntity(this.xCoord + 1, this.yCoord, this.zCoord);
    		}
    		if (this.func_145977_a(this.xCoord, this.yCoord, this.zCoord - 1))
    		{
    			this.adjacentChestZNeg = (TileEntityLockedChest)this.worldObj.getTileEntity(this.xCoord, this.yCoord, this.zCoord - 1);
    		}
    		if (this.func_145977_a(this.xCoord, this.yCoord, this.zCoord + 1))
    		{
    			this.adjacentChestZPos = (TileEntityLockedChest)this.worldObj.getTileEntity(this.xCoord, this.yCoord, this.zCoord + 1);
    		}
    		if (this.adjacentChestZNeg != null)
    		{
    			this.adjacentChestZNeg.func_145978_a(this, 0);
    		}
    		if (this.adjacentChestZPos != null)
    		{
    			this.adjacentChestZPos.func_145978_a(this, 2);
    		}
    		if (this.adjacentChestXPos != null)
    		{
    			this.adjacentChestXPos.func_145978_a(this, 1);
    		}
    		if (this.adjacentChestXNeg != null)
    		{
    			this.adjacentChestXNeg.func_145978_a(this, 3);
    		}
    	}
    }
    private boolean func_145977_a(int p_145977_1_, int p_145977_2_, int p_145977_3_)
    {
    Block block = this.worldObj.getBlock(p_145977_1_, p_145977_2_, p_145977_3_);
    return block instanceof BlockLockedChest && ((BlockLockedChest)block).field_149956_a == this.func_145980_j();
    }
    @Override
    public int func_145980_j()
    {
        if (this.cachedChestType == -1)
        {
            if (this.worldObj == null || !(this.getBlockType() instanceof BlockLockedChest))
            {
                return 0;
            }

            this.cachedChestType = ((BlockLockedChest)this.getBlockType()).field_149956_a;
        }
        
        return this.cachedChestType;
    }

}

Link to comment
Share on other sites

You want two things:

 

1)

	@Override
public Packet getDescriptionPacket() {
	NBTTagCompound nbtTag = new NBTTagCompound();
	writeToNBT(nbtTag);
	return new S35PacketUpdateTileEntity(xCoord, yCoord, zCoord, 1, nbtTag);
}

@Override
public void onDataPacket(NetworkManager net, S35PacketUpdateTileEntity packet) {
	readFromNBT(packet.func_148857_g());
}

 

2) Whenever the inventory changes

if (worldObj != null) worldObj.markBlockForUpdate(xCoord, yCoord, zCoord);

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

Even with putting the two methods in my tileentitylockedchest file and the

if (worldObj != null) worldObj.markBlockForUpdate(xCoord, yCoord, zCoord);

in the setInventorySlotContents() method, nothing changed  :(

 

This is what the tileentitylockedchest file looks like now

package com.angelo.venturemod.tileentities;

import java.util.Iterator;
import java.util.List;

import com.angelo.venturemod.blocks.BlockLockedChest;

import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.block.Block;
import net.minecraft.block.BlockChest;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.inventory.ContainerChest;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.InventoryLargeChest;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.Packet;
import net.minecraft.network.play.server.S35PacketUpdateTileEntity;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.tileentity.TileEntityChest;
import net.minecraft.util.AxisAlignedBB;

public class TileEntityLockedChest extends TileEntityChest{


private ItemStack[] chestContents = new ItemStack[36];
    
    /** Contains the chest tile located adjacent to this one (if any) */
    public TileEntityLockedChest adjacentChestZNeg;
    /** Contains the chest tile located adjacent to this one (if any) */
    public TileEntityLockedChest adjacentChestXPos;
    /** Contains the chest tile located adjacent to this one (if any) */
    public TileEntityLockedChest adjacentChestXNeg;
    /** Contains the chest tile located adjacent to this one (if any) */
    public TileEntityLockedChest adjacentChestZPos;
    
    private int cachedChestType;
    private String customName;
    
    /**
     * Called when a client event is received with the event number and argument, see World.sendClientEvent
     */
    public boolean receiveClientEvent(int p_145842_1_, int p_145842_2_)
    {
        if (p_145842_1_ == 1)
        {
            this.numPlayersUsing = p_145842_2_;
            
            return true;
        }
        else
        {
        	
            return super.receiveClientEvent(p_145842_1_, p_145842_2_);
            
        }
    }
    
    @Override
public ItemStack decrStackSize(int p_70298_1_, int p_70298_2_) {
    	
    	if (this.chestContents[p_70298_1_] != null)
        {
            ItemStack itemstack;

            if (this.chestContents[p_70298_1_].stackSize <= p_70298_2_)
            {
                itemstack = this.chestContents[p_70298_1_];
                this.chestContents[p_70298_1_] = null;
                markDirty();
                if (worldObj != null) worldObj.markBlockForUpdate(xCoord, yCoord, zCoord);
                return itemstack;
            }
            else
            {
                itemstack = this.chestContents[p_70298_1_].splitStack(p_70298_2_);

                if (this.chestContents[p_70298_1_].stackSize == 0)
                {
                    this.chestContents[p_70298_1_] = null;
                }

                markDirty();
                if (worldObj != null) worldObj.markBlockForUpdate(xCoord, yCoord, zCoord);
                return itemstack;
            }
        }
        else
        {
            return null;
        }
}
    @Override
    public void markDirty()
    {
       super.markDirty();
       
       
    } 
    /**
     * Returns the name of the inventory
     */
    @Override
    public String getInventoryName()
    {
        return this.hasCustomInventoryName() ? this.customName : "Locked Chest";
    }
    
    @Override
    public void setInventorySlotContents(int i, ItemStack itemstack)
    {
    	if (worldObj != null){
    		worldObj.markBlockForUpdate(xCoord, yCoord, zCoord);
    	}
    	
    	chestContents[i] = itemstack;
    	if (itemstack != null && itemstack.stackSize > getInventoryStackLimit())
    	{
    		itemstack.stackSize = getInventoryStackLimit();
    	}
    	
    	markDirty();
    }
    
    @Override
    public void readFromNBT(NBTTagCompound p_145839_1_)
    {
    	super.readFromNBT(p_145839_1_);
    	NBTTagList nbttaglist = p_145839_1_.getTagList("Items", 10);
    	this.chestContents = new ItemStack[this.getSizeInventory()];
    	if (p_145839_1_.hasKey("Locked Chest", )
    	{
    		this.customName = p_145839_1_.getString("Locked Chest");
    	}
    	for (int i = 0; i < nbttaglist.tagCount(); ++i)
    	{
    		NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i);
    		int j = nbttagcompound1.getByte("Slot") & 255;
    		if (j >= 0 && j < this.chestContents.length)
    		{
    			this.chestContents[j] = ItemStack.loadItemStackFromNBT(nbttagcompound1);
    		}
    	}
    }
    @Override
    public void writeToNBT(NBTTagCompound p_145841_1_)
    {
        super.writeToNBT(p_145841_1_);
        NBTTagList nbttaglist = new NBTTagList();

        for (int i = 0; i < this.chestContents.length; ++i)
        {
            if (this.chestContents[i] != null)
            {
                NBTTagCompound nbttagcompound1 = new NBTTagCompound();
                nbttagcompound1.setByte("Slot", (byte)i);
                this.chestContents[i].writeToNBT(nbttagcompound1);
                nbttaglist.appendTag(nbttagcompound1);
                
            }
        }

        p_145841_1_.setTag("Items", nbttaglist);
        
        if (this.hasCustomInventoryName())
        {
            p_145841_1_.setString("Locked Chest", this.customName);
        }
        
    }

    private void func_145978_a(TileEntityLockedChest p_145978_1_, int p_145978_2_){
    if (p_145978_1_.isInvalid())
    {
        this.adjacentChestChecked = false;
    }
    else if (this.adjacentChestChecked)
    {
        switch (p_145978_2_)
        {
            case 0:
                if (this.adjacentChestZPos != p_145978_1_)
                {
                    this.adjacentChestChecked = false;
                }

                break;
            case 1:
                if (this.adjacentChestXNeg != p_145978_1_)
                {
                    this.adjacentChestChecked = false;
                }

                break;
            case 2:
                if (this.adjacentChestZNeg != p_145978_1_)
                {
                    this.adjacentChestChecked = false;
                }

                break;
            case 3:
                if (this.adjacentChestXPos != p_145978_1_)
                {
                    this.adjacentChestChecked = false;
                }
        }
    }
    }
    
    /**
    * Performs the check for adjacent chests to determine if this chest is double or not.
    */
    @Override
    public void checkForAdjacentChests()
    {
    	if (!this.adjacentChestChecked)
    	{
    		this.adjacentChestChecked = true;
    		this.adjacentChestZNeg = null;
    		this.adjacentChestXPos = null;
    		this.adjacentChestXNeg = null;
    		this.adjacentChestZPos = null;
    		if (this.func_145977_a(this.xCoord - 1, this.yCoord, this.zCoord))
    		{
    			this.adjacentChestXNeg = (TileEntityLockedChest)this.worldObj.getTileEntity(this.xCoord - 1, this.yCoord, this.zCoord);
    		}
    		if (this.func_145977_a(this.xCoord + 1, this.yCoord, this.zCoord))
    		{
    			this.adjacentChestXPos = (TileEntityLockedChest)this.worldObj.getTileEntity(this.xCoord + 1, this.yCoord, this.zCoord);
    		}
    		if (this.func_145977_a(this.xCoord, this.yCoord, this.zCoord - 1))
    		{
    			this.adjacentChestZNeg = (TileEntityLockedChest)this.worldObj.getTileEntity(this.xCoord, this.yCoord, this.zCoord - 1);
    		}
    		if (this.func_145977_a(this.xCoord, this.yCoord, this.zCoord + 1))
    		{
    			this.adjacentChestZPos = (TileEntityLockedChest)this.worldObj.getTileEntity(this.xCoord, this.yCoord, this.zCoord + 1);
    		}
    		if (this.adjacentChestZNeg != null)
    		{
    			this.adjacentChestZNeg.func_145978_a(this, 0);
    		}
    		if (this.adjacentChestZPos != null)
    		{
    			this.adjacentChestZPos.func_145978_a(this, 2);
    		}
    		if (this.adjacentChestXPos != null)
    		{
    			this.adjacentChestXPos.func_145978_a(this, 1);
    		}
    		if (this.adjacentChestXNeg != null)
    		{
    			this.adjacentChestXNeg.func_145978_a(this, 3);
    		}
    	}
    }
    private boolean func_145977_a(int p_145977_1_, int p_145977_2_, int p_145977_3_)
    {
    Block block = this.worldObj.getBlock(p_145977_1_, p_145977_2_, p_145977_3_);
    return block instanceof BlockLockedChest && ((BlockLockedChest)block).field_149956_a == this.func_145980_j();
    }
    
    @Override
public Packet getDescriptionPacket() {
	NBTTagCompound nbtTag = new NBTTagCompound();
	writeToNBT(nbtTag);
	return new S35PacketUpdateTileEntity(xCoord, yCoord, zCoord, 1, nbtTag);
}

@Override
public void onDataPacket(NetworkManager net, S35PacketUpdateTileEntity packet) {
	readFromNBT(packet.func_148857_g());

}
    
    @Override
    public int func_145980_j()
    {
        if (this.cachedChestType == -1)
        {
            if (this.worldObj == null || !(this.getBlockType() instanceof BlockLockedChest))
            {
                return 0;
            }

            this.cachedChestType = ((BlockLockedChest)this.getBlockType()).field_149956_a;
        }
        
        return this.cachedChestType;
    }

}

 

This is where I put that if statement:

@Override
    public void setInventorySlotContents(int i, ItemStack itemstack)
    {
    	if (worldObj != null){
    		worldObj.markBlockForUpdate(xCoord, yCoord, zCoord);
    	}
    	
    	chestContents[i] = itemstack;
    	if (itemstack != null && itemstack.stackSize > getInventoryStackLimit())
    	{
    		itemstack.stackSize = getInventoryStackLimit();
    	}
    	
    	markDirty();
    }
    

 

 

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.



  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • I made a block entity in forge 1.20.1, I want to prevent hopper from taking input slot item, i tried to override the extractItem method, it prevented hopper from taking input slot item, but the player also unable to take/change the item in input slot unless the slot is empty. public class FluidSeparatorBlockEntity extends BlockEntity implements MenuProvider { private static final int INPUT_SLOT = 0; private final CustomItemHandler itemHandler = new CustomItemHandler(3){ @Override protected void onContentsChanged(int slot) { setChanged(); } @Override public boolean isItemValid(int slot, @NotNull ItemStack stack) { return slot == INPUT_SLOT; } @Override public @NotNull ItemStack extractItem(int slot, int amount, boolean simulate) { if (slot == INPUT_SLOT) { return ItemStack.EMPTY; } return super.extractItem(slot, amount, simulate); } }; private LazyOptional<IItemHandler> lazyItemHandler = LazyOptional.empty(); protected final ContainerData data; private int progress = 0; private int maxProgress = 78; public FluidSeparatorBlockEntity(BlockPos pPos, BlockState pBlockState) { super(ModBlockEntities.FLUID_SEPARATOR_BE.get(), pPos, pBlockState); this.data = new ContainerData() { @Override public int get(int pIndex) { return switch (pIndex) { case 0 -> FluidSeparatorBlockEntity.this.progress; case 1, 2 -> FluidSeparatorBlockEntity.this.maxProgress; default -> 0; }; } @Override public void set(int pIndex, int pValue) { switch (pIndex) { case 0 -> FluidSeparatorBlockEntity.this.progress = pValue; case 1, 2 -> FluidSeparatorBlockEntity.this.maxProgress = pValue; } } @Override public int getCount() { return 3; } }; } @Override public @NotNull <T> LazyOptional<T> getCapability(@NotNull Capability<T> cap, @Nullable Direction side) { if(cap == ForgeCapabilities.ITEM_HANDLER) { return lazyItemHandler.cast(); } return super.getCapability(cap, side); } @Override public void onLoad() { super.onLoad(); lazyItemHandler = LazyOptional.of(() -> itemHandler); } @Override public void invalidateCaps() { super.invalidateCaps(); lazyItemHandler.invalidate(); } public void drops() { SimpleContainer inventory = new SimpleContainer(itemHandler.getSlots()); for(int i = 0; i < itemHandler.getSlots(); i++) { inventory.setItem(i, itemHandler.getStackInSlot(i)); } Containers.dropContents(this.level, this.worldPosition, inventory); } @Override public Component getDisplayName() { return Component.translatable("block.chemmaster.fluid_separator"); } @Nullable @Override public AbstractContainerMenu createMenu(int pContainerId, Inventory pPlayerInventory, Player pPlayer) { return new FluidSeparatorMenu(pContainerId, pPlayerInventory, this, this.data); } @Override protected void saveAdditional(CompoundTag pTag) { pTag.put("inventory", itemHandler.serializeNBT()); pTag.putInt("fluid_separator.progress", progress); super.saveAdditional(pTag); } @Override public void load(CompoundTag pTag) { super.load(pTag); itemHandler.deserializeNBT(pTag.getCompound("inventory")); progress = pTag.getInt("fluid_separator.progress"); } public void tick(Level pLevel, BlockPos pPos, BlockState pState) { ItemStack inputStack = this.itemHandler.getStackInSlot(INPUT_SLOT); if (inputStack.getCount() < 2) { resetProgress(); return; } if(hasRecipe()) { increaseCraftingProgress(); setChanged(pLevel, pPos, pState); if(hasProgressFinished()) { craftItem(); resetProgress(); } } else { resetProgress(); } } private void resetProgress() { progress = 0; } private void craftItem() { Optional<FluidSeparatingRecipe> recipe = getCurrentRecipe(); if (recipe.isPresent()) { List<ItemStack> results = recipe.get().getOutputs(); ItemStack inputStack = this.itemHandler.getStackInSlot(INPUT_SLOT); if (inputStack.getCount() < 2) { // If there are not enough items, do not proceed with crafting return; } // Extract the input item from the input slot this.itemHandler.internalExtractItem(INPUT_SLOT, 2, false); // Loop through each result item and find suitable output slots for (ItemStack result : results) { int outputSlot = findSuitableOutputSlot(result); if (outputSlot != -1) { this.itemHandler.setStackInSlot(outputSlot, new ItemStack(result.getItem(), this.itemHandler.getStackInSlot(outputSlot).getCount() + result.getCount())); } else { // Handle the case where no suitable output slot is found // This can be logging an error, throwing an exception, or any other handling logic System.err.println("No suitable output slot found for item: " + result); } } } } private int findSuitableOutputSlot(ItemStack result) { // Implement logic to find a suitable output slot for the given result // Return the slot index or -1 if no suitable slot is found for (int i = 0; i < this.itemHandler.getSlots(); i++) { // Ensure we do not place the output item in the input slot if (i == INPUT_SLOT) { continue; } ItemStack stackInSlot = this.itemHandler.getStackInSlot(i); if (stackInSlot.isEmpty() || (stackInSlot.getItem() == result.getItem() && stackInSlot.getCount() + result.getCount() <= stackInSlot.getMaxStackSize())) { return i; } } return -1; } private boolean hasRecipe() { Optional<FluidSeparatingRecipe> recipe = getCurrentRecipe(); if (recipe.isEmpty()) { return false; } List<ItemStack> results = recipe.get().getOutputs(); for (ItemStack result : results) { if (!canInsertAmountIntoOutputSlot(result) || !canInsertItemIntoOutputSlot(result.getItem())) { return false; } } return true; } private Optional<FluidSeparatingRecipe> getCurrentRecipe(){ SimpleContainer inventory = new SimpleContainer(this.itemHandler.getSlots()); for (int i = 0; i < itemHandler.getSlots(); i++) { inventory.setItem(i, this.itemHandler.getStackInSlot(i)); } return this.level.getRecipeManager().getRecipeFor(FluidSeparatingRecipe.Type.INSTANCE, inventory, level); } private boolean canInsertAmountIntoOutputSlot(ItemStack result) { for (int i = 1; i < this.itemHandler.getSlots(); i++) { ItemStack stackInSlot = this.itemHandler.getStackInSlot(i); if (stackInSlot.isEmpty() || (stackInSlot.getItem() == result.getItem() && stackInSlot.getCount() + result.getCount() <= stackInSlot.getMaxStackSize())) { return true; } } return false; } private boolean canInsertItemIntoOutputSlot(Item item) { for (int i = 1; i < this.itemHandler.getSlots(); i++) { ItemStack stackInSlot = this.itemHandler.getStackInSlot(i); if (stackInSlot.isEmpty() || stackInSlot.getItem() == item) { return true; } } return false; } private boolean hasProgressFinished() { return progress >= maxProgress; } private void increaseCraftingProgress() { progress++; } }  
    • No dice. Unfortunately this fix didn't work, thank you though.
    • Maybe you need a rayon mod. https://www.curseforge.com/minecraft/mc-mods/rayon
    • Not sure what's going on the logs are making even less sense than usual to me. Any help would be much appreciated.   https://paste.ee/p/KBHyP#s=0
  • Topics

  • Who's Online (See full list)

×
×
  • Create New...

Important Information

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