- Home /
How to make a for loop display inventory correctly?
I've been stuck on this issue a while now, I have a working inventory and shop system, however when I try to display it with GUI, it comes out wrong. Here's a pic of what's currently in the inventory(added at runtime from the shop).
Here is the script that's supposed to loop through it:
for(loopInt = 0; loopInt < inventoryContents.Count; loopInt++)
{
InventoryItem inventoryItemScript = inventoryItem.GetComponent<InventoryItem>();
if(targetPath.transform.childCount >= inventoryContents.Count)
{
targetPath.transform.GetChild(targetPath.transform.childCount); //Prevents clones
gridControlScript.Reposition(); //Organizes the inv with NGUI's grid
inventoryItemScript.UpdateInfo(); //Makes sure all the info is correct
}
else
{
NGUITools.AddChild(targetPath, inventoryItem);
inventoryItemScript.item.itemName = inventoryContents[loopInt].itemName;
inventoryItemScript.item.icon = inventoryContents[loopInt].icon;
inventoryItemScript.UpdateInfo(); //Makes sure all the info is correct
gridControlScript.Reposition(); //Organizes the inv with NGUI's grid
}
}
NGUITools.AddChild is basically like instantiate but optimized for NGUI. gridControlScript.Reposition() is not important, just an NGUI thing that organizes the buttons.
Here is what inventoryItemScript.UpdateInfo() does:
public void UpdateInfo()
{
itemNameTag = transform.Find("Item Text");
itemNameTag.GetComponent<UILabel>().text = item.itemName;
itemIcon = transform.Find("Texture");
itemIcon.GetComponent<UITexture>().mainTexture = item.icon;
}
I've checked and it does find the right Game Objects at runtime. However it doesn't seem to be getting the right info from the inventory for loop. Here's a pic in the inspector:
What's even odder is that this is what I actually see in the game screen:
All the info is completely different! And I have no idea why.
Drag the pictures into a new tab to see them more clearly.
InventoryItem inventoryItemScript = inventoryItem.GetComponent<InventoryItem>();
You're always getting the same Component, but you want to loop through all InventoryItems. If I remember correctly you can pass GetComponent an index-value, in your case loopInt.
Also, if you're not sure WHY your script isn't doing what you want, put in some Debug-Logs so you can follow each step it does. Should help you to locate the problem more quickly. :)
Your answer
Follow this Question
Related Questions
Why wont inventory wont update after or more purchases from in-game shop? 1 Answer
crazy loop !!! HELP ME 1 Answer
For loop not working 1 Answer
x=x Assignment made to same variable 3 Answers