randomcoder
randomcoder

Reputation: 646

Unity Inventory stacking not functioning properly

I'm a beginner at Unity.

I'm trying to make an inventory system where if you have say 4 wood, it would not take up 4 inventory spaces, only 1 that has a number 4.

When I get 4 wood normally, and open the inventory, it works fine, with the wood icon and the number 4. When I add using the inspector to a public List, it just duplicates the first entry. Here's what I'm talking about. Here's the code:

public void OpenInventory()
{

    inventoryPanel.SetActive(true);
    Dictionary<string, int> stuff = new Dictionary<string, int>();
    stuff = new Dictionary<string, int>();
    //updating inventory slots on screen
    for (int i = 0; i < inv.Count; i++)
    {
        if (!stuff.ContainsKey(inv[i]))
        {
            stuff.Add(inv[i], 1);  
        }
        else
        {
            stuff[inv[i]] = stuff[inv[i]] += 1;
        }

    }

    for (int i = 0; i < stuff.Count; i++)
    {
        uiSlots[i].GetChild(0).gameObject.GetComponent<Image>().sprite = Resources.Load<Sprite>("Sprites/" + inv[i]) as Sprite;

        uiSlots[i].GetChild(1).GetComponent<Text>().text = stuff[inv[i]].ToString();

    }


}

Before I make changes (working fine):

Before I make changes

still before but the graphical thingy

Now, when I change the inventory in inspector and refresh the inventory screen:

after I make changes

still after I make changes

I genuinely have no idea what is going on, especially because if I do the same thing again, nothing changes.

Upvotes: 1

Views: 194

Answers (1)

MyBug18
MyBug18

Reputation: 2230

Let's look at this code snip.

for (int i = 0; i < stuff.Count; i++)
    {
        uiSlots[i].GetChild(0).gameObject.GetComponent<Image>().sprite = Resources.Load<Sprite>("Sprites/" + inv[i]) as Sprite;

        uiSlots[i].GetChild(1).GetComponent<Text>().text = stuff[inv[i]].ToString();

    }

In your case, the stuff.Count == 2, right? Wood and troll. So i in your for loop will iterate over 0, 1, which means inv[i] will always be wood! You got it? The first and second element of inv is both wood, so it's no surprise that there are two wood slots in your inventory.

Here's my suggestion, use foreach:

int walker = 0; // which indicates the index of slot.

foreach (var item in stuff)
    {
        uiSlots[walker].GetChild(0).gameObject.GetComponent<Image>().sprite = Resources.Load<Sprite>("Sprites/" + item.Key) as Sprite;

        uiSlots[walker].GetChild(1).GetComponent<Text>().text = item.Value.ToString();

        walker++;
    }

foreach can iterate all kinds of collections. The process that you put the items in inv into stuff dict can also be converted into foreach expression, like:

foreach (var item in inv)
    {
        if (!stuff.ContainsKey(item))
        {
            stuff.Add(item, 1);  
        }
        else
        {
            stuff[item]++;
        }
    }

Upvotes: 1

Related Questions