Home > OS >  foreach loop only executing all code on the first iteration, selectively executing code on further i
foreach loop only executing all code on the first iteration, selectively executing code on further i

Time:09-25

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 enter image description here

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

  • Related