Jump to content

[Solved][1.12.2] Custom item inventory slot not keeping contents.


TheMCJavaFre4k

Recommended Posts

Hi there

My aim was to create a single slot inventory when an item was right clicked. Im good with all the gui stuff but can seem to nail the capabilities and NBT. 

I found this post(

I also don't know using the current setup how I would go about accessing the contents of the slot from within the item class.

 

Any guidance is appreciated.

 

Code:

ItemClass:

package net.themcjavafre4k.mcdj.item.headphones;

import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.EntityEquipmentSlot;
import net.minecraft.item.ItemArmor;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ActionResult;
import net.minecraft.util.EnumActionResult;
import net.minecraft.util.EnumHand;
import net.minecraft.world.World;
import net.minecraftforge.common.capabilities.ICapabilityProvider;
import net.minecraftforge.items.CapabilityItemHandler;
import net.minecraftforge.items.IItemHandler;
import net.themcjavafre4k.mcdj.MCDJGuiHandler;
import net.themcjavafre4k.mcdj.MCDJMod;
import net.themcjavafre4k.mcdj.item.CustomRecord;
import net.themcjavafre4k.mcdj.item.MCDJItems;

public class ItemHeadphones extends ItemArmor{

	private String title;

	public ItemHeadphones(String name){
		super(MCDJItems.headphoneMaterial, 1, EntityEquipmentSlot.HEAD);
		this.title = name;
		setUnlocalizedName(name);
		setRegistryName(name);
		setCreativeTab(MCDJMod.creativeTab);
		INSTANCE = this;
	}

	public void registerItemModel(){
		MCDJMod.proxy.registerItemRenderer(this, 0, title, "mcdj");
	}

	@Override
	public ActionResult<ItemStack> onItemRightClick(World world, EntityPlayer player, EnumHand hand){
		ItemStack itemstack = player.getHeldItem(hand);

		if (!world.isRemote){
			player.openGui(MCDJMod.instance, MCDJGuiHandler.HEADPHONES, world, (int)player.posX, (int)player.posY, (int)player.posZ);
			//LogHelper.info("Succesfully opened GUI");
		}

		return new ActionResult<ItemStack>(EnumActionResult.PASS, player.getHeldItemMainhand());
	}

	@Override
	public ICapabilityProvider initCapabilities( ItemStack item, NBTTagCompound nbt ) {
		return new HeadphonesProvider();
	}

}

 

Provider:

package net.themcjavafre4k.mcdj.item.headphones;

import net.minecraft.nbt.NBTBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumFacing;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.ICapabilityProvider;
import net.minecraftforge.common.capabilities.ICapabilitySerializable;
import net.minecraftforge.items.CapabilityItemHandler;
import net.minecraftforge.items.ItemStackHandler;

public class HeadphonesProvider implements ICapabilityProvider, ICapabilitySerializable<NBTTagCompound>{

	private ItemStackHandler inventory;

	public HeadphonesProvider() {
		inventory = new ItemStackHandler(1);
	}

	@Override
	public NBTTagCompound serializeNBT() {
		return inventory.serializeNBT();
	}

	@Override
	public void deserializeNBT( NBTTagCompound nbt ) {
		// nbt = new NBTTagCompound();
    	inventory.deserializeNBT(nbt);

	}

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

	@Override
	public <T> T getCapability( Capability<T> capability, EnumFacing facing ) {
		if( capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY ) {
			return (T) inventory; 
		}
		return null;
	}
	
	
}

 

Container:

package net.themcjavafre4k.mcdj.item.headphones;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.items.IItemHandler;
import net.themcjavafre4k.mcdj.inventory.SlotInput;
import net.themcjavafre4k.mcdj.item.CustomRecord;
import net.themcjavafre4k.mcdj.item.MCDJItems;

public class ContainerHeadphones extends Container{

	public IItemHandler inv;

	public ContainerHeadphones(IItemHandler itemHandler, EntityPlayer player ) {

		this.inv = itemHandler;

		addSlotToContainer(new SlotInput(itemHandler, 0, 44, 35));

		for(int i = 0; i < 3; i++){
			for(int j = 0; j < 9; j++){
				addSlotToContainer(new Slot(player.inventory, j+i*9+9, 8+j*18, 84+i*18));
			}
		}

		for(int i = 0; i < 9; i++){
			addSlotToContainer(new Slot(player.inventory, i, 8+i*18, 142));
		}

	}

	@Override
	public boolean canInteractWith(EntityPlayer playerIn) {
		return true;
	}

	//Crashing game
	//	@Nullable
	//	@Override
	//	public ItemStack transferStackInSlot(EntityPlayer playerIn, int index)
	//    {
	//        ItemStack itemstack = ItemStack.EMPTY;
	//        Slot slot = this.inventorySlots.get(index);
	//
	//        if (slot != null && slot.getHasStack())
	//        {
	//            ItemStack itemstack1 = slot.getStack();
	//            itemstack = itemstack1.copy();
	//
	//            if (index == 2)
	//            {
	//                if (!this.mergeItemStack(itemstack1, 3, 39, true))
	//                {
	//                    return ItemStack.EMPTY;
	//                }
	//
	//                slot.onSlotChange(itemstack1, itemstack);
	//            }
	//            else if (!this.mergeItemStack(itemstack1, 3, 39, false))
	//            {
	//                return ItemStack.EMPTY;
	//            }
	//
	//            if (itemstack1.isEmpty())
	//            {
	//                slot.putStack(ItemStack.EMPTY);
	//            }
	//            else
	//            {
	//                slot.onSlotChanged();
	//            }
	//
	//            if (itemstack1.getCount() == itemstack.getCount())
	//            {
	//                return ItemStack.EMPTY;
	//            }
	//
	//            slot.onTake(playerIn, itemstack1);
	//        }
	//
	//        return itemstack;
	//    }



}

 

SlotInput:

package net.themcjavafre4k.mcdj.inventory;

import javax.annotation.Nonnull;

import net.minecraft.item.ItemStack;
import net.minecraftforge.items.IItemHandler;
import net.minecraftforge.items.SlotItemHandler;
import net.themcjavafre4k.mcdj.item.CustomRecord;
import net.themcjavafre4k.mcdj.item.MCDJItems;


public class SlotInput extends SlotItemHandler {
	public SlotInput(IItemHandler inventory, int par2, int par3, int par4) {
		super(inventory, par2, par3, par4);
	}

	@Override
	public boolean isItemValid(ItemStack itemstack) {
		return itemstack.getItem() instanceof CustomRecord;
		//return true;
	}

	@Override
	public int getSlotStackLimit() {
		return 1;
	}
	
	
}

 

Gui:

package net.themcjavafre4k.mcdj.item.headphones;

import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.resources.I18n;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import net.themcjavafre4k.mcdj.MCDJMod;
import net.themcjavafre4k.mcdj.SoundHandler;
import net.themcjavafre4k.mcdj.item.MCDJItems;


@SideOnly(Side.CLIENT)
public class GuiHeadphones extends GuiContainer{

	private static final ResourceLocation BG_TEXTURE = new ResourceLocation(MCDJMod.modId, "textures/gui/headphonegui.png");

	public GuiHeadphones(Container container, InventoryPlayer inventory) {
		super(container);

	}

	@Override
	public void initGui(){
		super.initGui();
	}

	@Override
	public void drawScreen(int mouseX, int mouseY, float partialTicks) {
		this.drawDefaultBackground();
		super.drawScreen(mouseX, mouseY, partialTicks);
		this.renderHoveredToolTip(mouseX, mouseY);
	}

	@Override
	protected void drawGuiContainerBackgroundLayer(float partialTicks, int mouseX, int mouseY){
		GlStateManager.color(1, 1, 1, 1);
		mc.getTextureManager().bindTexture(BG_TEXTURE);
		int x = (width - xSize) / 2;
		int y = (height - ySize) / 2;
		drawTexturedModalRect(x, y, 0, 0, xSize, ySize);
	}

	@Override
	protected void drawGuiContainerForegroundLayer(int mousX, int mouseY){
		String name = I18n.format(MCDJItems.headphones.getUnlocalizedName());
		//fontRenderer.drawString("Search For Songs", 195, 4, 0xFFFFFF);
		fontRenderer.drawString("Headphone Player", (xSize/2 - fontRenderer.getStringWidth(name)/2), 5, 0xFFFFFF);
		//fontRenderer.drawString(invPlayer.getDisplayName().getUnformattedText(), 8, ySize/2 - 10, 0xFFFFFF);
	}


}

 If any more information is needed I will provide.

Edited by TheMCJavaFre4k
Solved
Link to comment
Share on other sites

Have you searched the forums for similar topics? If I remember correctly there was a topic about something very similar not long ago, and I think the person posted their working code at the end.

 

EDIT- have a read of this

http://www.minecraftforge.net/forum/topic/63240-1122-checking-a-specific-container-for-items/

Edited by Cadiboo

About Me

Spoiler

My Discord - Cadiboo#8887

My WebsiteCadiboo.github.io

My ModsCadiboo.github.io/projects

My TutorialsCadiboo.github.io/tutorials

Versions below 1.14.4 are no longer supported on this forum. Use the latest version to receive support.

When asking support remember to include all relevant log files (logs are found in .minecraft/logs/), code if applicable and screenshots if possible.

Only download mods from trusted sites like CurseForge (minecraft.curseforge.com). A list of bad sites can be found here, with more information available at stopmodreposts.org

Edit your own signature at www.minecraftforge.net/forum/settings/signature/ (Make sure to check its compatibility with the Dark Theme)

Link to comment
Share on other sites

1 minute ago, Cadiboo said:

Have you searched the forums for similar topics? If I remember correctly there was a topic about something very similar not long ago, and I think the person posted their working code at the end.

 The only real similar one i found was the one i referenced in the post. All others seem to be regarding tile entities with the same issues. Will have another look though.

Link to comment
Share on other sites

One thing that I can see that is important is the transferStackInSlot function you say its crashing the game?

Here is my implementation of it (for a Tile entity, it might not work for an item)

@Override
	public ItemStack transferStackInSlot(EntityPlayer player, int index) {
		/*
		ITS POSSIBLE to have multi-line comments
		*/
		//WIPTech.logger.info("transferStackInSlot: "+ inventorySlots.get(index).getStack());
		ItemStack itemstack = ItemStack.EMPTY;
		Slot slot = inventorySlots.get(index);

		if (slot != null && slot.getHasStack()) {
			ItemStack itemstack1 = slot.getStack();
			itemstack = itemstack1.copy();

			int containerSlots = inventorySlots.size() - player.inventory.mainInventory.size();

			if (index < containerSlots) {
				if (!this.mergeItemStack(itemstack1, containerSlots, inventorySlots.size(), true)) {
					return ItemStack.EMPTY;
				}
			} else if (!this.mergeItemStack(itemstack1, 0, containerSlots, false)) {
				return ItemStack.EMPTY;
			}

			if (itemstack1.getCount() == 0) {
				slot.putStack(ItemStack.EMPTY);
			} else {
				slot.onSlotChanged();
			}

			if (itemstack1.getCount() == itemstack.getCount()) {
				return ItemStack.EMPTY;
			}

			slot.onTake(player, itemstack1);
		}

		return itemstack;
	}

 

About Me

Spoiler

My Discord - Cadiboo#8887

My WebsiteCadiboo.github.io

My ModsCadiboo.github.io/projects

My TutorialsCadiboo.github.io/tutorials

Versions below 1.14.4 are no longer supported on this forum. Use the latest version to receive support.

When asking support remember to include all relevant log files (logs are found in .minecraft/logs/), code if applicable and screenshots if possible.

Only download mods from trusted sites like CurseForge (minecraft.curseforge.com). A list of bad sites can be found here, with more information available at stopmodreposts.org

Edit your own signature at www.minecraftforge.net/forum/settings/signature/ (Make sure to check its compatibility with the Dark Theme)

Link to comment
Share on other sites

Just now, TyrellPlayz said:

What's the capability for?

Capabilities in general or in this specific context?

About Me

Spoiler

My Discord - Cadiboo#8887

My WebsiteCadiboo.github.io

My ModsCadiboo.github.io/projects

My TutorialsCadiboo.github.io/tutorials

Versions below 1.14.4 are no longer supported on this forum. Use the latest version to receive support.

When asking support remember to include all relevant log files (logs are found in .minecraft/logs/), code if applicable and screenshots if possible.

Only download mods from trusted sites like CurseForge (minecraft.curseforge.com). A list of bad sites can be found here, with more information available at stopmodreposts.org

Edit your own signature at www.minecraftforge.net/forum/settings/signature/ (Make sure to check its compatibility with the Dark Theme)

Link to comment
Share on other sites

  • 3 months later...

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.

Announcements



  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • WINNING303 DAFTAR SITUS JUDI SLOT RESMI TERPERCAYA 2024 Temukan situs judi slot resmi dan terpercaya untuk tahun 2024 di Winning303! Daftar sekarang untuk mengakses pengalaman berjudi slot yang aman dan terjamin. Dengan layanan terbaik dan reputasi yang kokoh, Winning303 adalah pilihan terbaik bagi para penggemar judi slot. Jelajahi berbagai pilihan permainan dan raih kesempatan besar untuk meraih kemenangan di tahun ini dengan Winning303 [[jumpuri:❱❱❱❱❱ DAFTAR DI SINI ❰❰❰❰❰ > https://w303.pink/orochimaru]] [[jumpuri:❱❱❱❱❱ DAFTAR DI SINI ❰❰❰❰❰ > https://w303.pink/orochimaru]]
    • SLOT PULSA TANPA POTONGAN : SLOT PULSA 5000 VIA INDOSAT IM3 TANPA POTONGAN - SLOT PULSA XL TELKOMSEL TANPA POTONGAN  KLIK DISINI DAFTAR DISINI SLOT VVIP << KLIK DISINI DAFTAR DISINI SLOT VVIP << KLIK DISINI DAFTAR DISINI SLOT VVIP << KLIK DISINI DAFTAR DISINI SLOT VVIP << SITUS SLOT GACOR 88 MAXWIN X500 HARI INI TERBAIK DAN TERPERCAYA GAMPANG MENANG Dunia Game gacor terus bertambah besar seiring berjalannya waktu, dan sudah tentu dunia itu terus berkembang serta merta bersamaan dengan berkembangnya SLOT GACOR sebagai website number #1 yang pernah ada dan tidak pernah mengecewakan sekalipun. Dengan banyaknya member yang sudah mempercayakan untuk terus menghasilkan uang bersama dengan SLOT GACOR pastinya mereka sudah percaya untuk bermain Game online bersama dengan kami dengan banyaknya testimoni yang sudah membuktikan betapa seringnya member mendapatkan jackpot besar yang bisa mencapai ratusan juta rupiah. Best online Game website that give you more money everyday, itu lah slogan yang tepat untuk bermain bersama SLOT GACOR yang sudah pasti menang setiap harinya dan bisa menjadikan bandar ini sebagai patokan untuk mendapatkan penghasilan tambahan yang efisien dan juga sesuatu hal yang fix setiap hari nya. Kami juga mendapatkan julukan sebagai Number #1 website bocor yang berarti terus memberikan member uang asli dan jackpot setiap hari nya, tidak lupa bocor itu juga bisa diartikan dalam bentuk berbagi promosi untuk para official member yang terus setia bermain bersama dengan kami. Berbagai provider Game terus bertambah banyak setiap harinya dan terus melakukan support untuk membuat para official member terus bisa menang dan terus maxwin dalam bentuk apapun maka itu langsung untuk feel free to try yourself, play with SLOT GACOR now or never !
    • BRI4D adalah pilihan tepat bagi Anda yang menginginkan pengalaman bermain slot dengan RTP tinggi dan transaksi yang akurat melalui Bank BRI. Berikut adalah beberapa alasan mengapa Anda harus memilih BRI4D: Tingkat Pengembalian (RTP) Tertinggi Kami bangga menjadi salah satu agen situs slot dengan RTP tertinggi, mencapai 99%! Ini berarti Anda memiliki peluang lebih besar untuk meraih kemenangan dalam setiap putaran permainan. Transaksi Melalui Bank BRI yang Akurat Proses deposit dan penarikan dana di BRI4D cepat, mudah, dan akurat. Kami menyediakan layanan transaksi melalui Bank BRI untuk kenyamanan Anda. Dengan begitu, Anda dapat melakukan transaksi dengan lancar dan tanpa khawatir. Beragam Pilihan Permainan BRI4D menyajikan koleksi permainan slot yang beragam dan menarik dari berbagai provider terkemuka. Mulai dari tema klasik hingga yang paling modern, Anda akan menemukan banyak pilihan permainan yang sesuai dengan selera dan preferensi Anda.  
    • SPARTA88 adalah pilihan tepat bagi Anda yang menginginkan agen situs slot terbaik dengan RTP tinggi dan transaksi yang mudah melalui Bank BNI. Berikut adalah beberapa alasan mengapa Anda harus memilih SPARTA88: Tingkat Pengembalian (RTP) Tinggi Kami bangga menjadi salah satu agen situs slot dengan RTP tertinggi, mencapai 98%! Ini berarti Anda memiliki peluang lebih besar untuk meraih kemenangan dalam setiap putaran permainan. Beragam Pilihan Permainan SPARTA88 menyajikan koleksi permainan slot yang beragam dan menarik dari berbagai provider terkemuka. Mulai dari tema klasik hingga yang paling modern, Anda akan menemukan banyak pilihan permainan yang sesuai dengan selera dan preferensi Anda. Kemudahan Bertransaksi Melalui Bank BNI Proses deposit dan penarikan dana di SPARTA88 cepat, mudah, dan aman. Kami menyediakan layanan transaksi melalui Bank BNI untuk kenyamanan Anda. Dengan begitu, Anda dapat melakukan transaksi dengan lancar tanpa perlu khawatir.
    • Slot Bank ALADIN atau Daftar slot Bank ALADIN bisa anda lakukan pada situs WINNING303 kapanpun dan dimanapun, Bermodalkan Hp saja anda bisa mengakses chat ke agen kami selama 24 jam full. keuntungan bergabung bersama kami di WINNING303 adalah anda akan mendapatkan bonus 100% khusus member baru yang bergabung dan deposit. Tidak perlu banyak, 5 ribu rupiah saja anda sudah bisa bermain bersama kami di WINNING303 . Tunggu apa lagi ? Segera Klik DAFTAR dan anda akan jadi Jutawan dalam semalam.
  • Topics

×
×
  • Create New...

Important Information

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