foreach loop only executing all code on the first iteration, selectively executing code on further iterations

Viewed 121

I'm just getting started with programing in unity and I can't figure out why this foreachloop is not working. For each element in the dictionary, I would like it to first print the name of the item, then print a message based on whether or not the player can afford the item. For some reason, it is printing the item name every iteration, but only printing the message the first iteration.

Here is my code:

void Start()
{  
    Dictionary<string, int> itemInventory = new Dictionary<string, int>()
    {
        { "Potion", 5 },
        { "Antidote", 7 },
        { "Aspirin", 1 }
    };

    int playerGold = 12;
    foreach (KeyValuePair<string, int> kvp in itemInventory)
    {
        Debug.LogFormat("Item: {0} - {1}g", kvp.Key, kvp.Value);
        if (kvp.Value <= playerGold)
            Debug.LogFormat("You can afford this!");
        else
            Debug.LogFormat("Sorry, you're too broke to afford this!");
    }

}

And this is what it's printing to the console:

Item: Potion- 5g

You can afford this!

Item: Antidote- 7g

Item: Aspirin- 1g

So I'm just not sure why it's not printing the message each time!

1 Answers

There's not enough in your screenshot - just a hint of it - but I believe you have the "collapse" button turned on in your console window. This groups similar output so you don't get spammed by the same debug output over and over again.

EDIT: Trying to find a screenshot as I don't currently have Unity installed on this box I found a similar question with the same answer on Unity Answers.

enter image description here

Source: https://answers.unity.com/questions/1837643/debuglog-prints-only-sometimes.html

Related