简体   繁体   中英

C# How to break out of a nested for loop and continue with a new loop?

I am making a quest system for my game in Unity2D. I stored all my different kind of quests inside a dictionary but only 5 quests to be picked randomly for the player. I used nested loops first to get 5 random numbers, and then another foreach loop to access the elements inside the dictionary and lastly planned to use another for loop to print out all the picked quests. However, I am having problem because it printed out 25times, instead of 5. Is there a way to break out of the 2nd loop and go into the 3rd loop? Thanks!

void Start()
{
    // missions
    missions.Add("Visit Mural Stops x ", 1);
    missions.Add("Collect Cards x ", 2);
    missions.Add("Fight Monsters x", 3);
    missions.Add("Collect Coins x ", 4);
    missions.Add("Collect Items x", 5);
    missions.Add("Fight SBM Boss x ", 6);
    missions.Add("Find Mural Stops  x", 7);

    var numbers = new List<int>(missions.Count);
    for (int i = 0; i < missions.Count; i++)
    {
        numbers.Add(i);
    }

    var randomNumbers = new int[text.Length];
    // text.Length is always 5, as I only have 5 mission texts

    for (int i = 0; i < randomNumbers.Length; i++)
    {
        var thisNumber = Random.Range(1, numbers.Count);
        randomNumbers[i] = numbers[thisNumber];
        numbers.RemoveAt(thisNumber);
        //Debug.Log("random " + randomNumbers[i]);

        foreach (KeyValuePair<string, int> pairs in missions)
        {
            if (pairs.Value == randomNumbers[i])
            {
                //Debug.Log(pairs.Key); // print out 5 missions

                missionText = pairs.Key;

                for (int j = 0; j < text.Length; j++)
                {
                    text[j].text = missionText; // it only print out the last picked quests
                    Debug.Log(missionText); // each picked quest is printed out 5 times instead of once
                    // how do i print out only 5 times inside this loop?
                }
            }
        }
    }
}

Your problem is your last loop:

for (int j = 0; j < text.Length; j++)
{
    text[j].text = missionText;
    Debug.Log(missionText);
}

This is running the Debug.Log five times - once for each value of j (and you say earlier that text.Length is always 5).

In comments you say want to print all the picked quests into my texts.

You already have an index for your text - i - since your randomNumbers array is the same length as your texts and indeed the whole point of randomNumbers seems to be to generate a random number for each entry of text . So rather than that loop I quoted what you want to do is:

text[i].text = missionText;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM