0
Follow
0
View

unity sets random options, continues if it encounters a repeat, and gets stuck in an infinite loop

edithnith 注册会员
2023-02-25 12:03

the reference answer GPT ᴼ ᴾ ᴱ ᴺ ᴬ ᴵ < br / > this code problems appeared in the loop, when encounter repeat options, through the continue statement skip, but if all options are repeated, The loop will go into an infinite loop, causing it to get stuck. To avoid this, add counters inside the loop and exit the loop when the counter exceeds a certain value, as follows:

int y = 0;
int counter = 0; //添加计数器
while (y <= 3 && counter < 100) //限制循环次数
{
    int l = 1;
    if (y != flag)
    {
        int j = Random.Range(2, 4);
        for (int i = 0; i < y; i++)
        {
            if (ArrayX[n][j] == Buttonlist[i].GetComponentInChildren<Text>().text)
            {
                l = 0;
                break; //当发现重复选项时,直接退出循环
            }
        }
        if (l == 0)
        {
            counter++;
            continue;
        }
        Buttonlist[y].onClick.AddListener(() => Wrong(Buttonlist[flag].GetComponentInChildren<Text>().text));
        Buttonlist[y].GetComponentInChildren<Text>().text = ArrayX[n][j];
        y++;
    }
    else
    {
        y++;
    }
    counter++;
}


In addition, if the number of loops is set less than 1, the loop can proceed but the last option is not assigned. The problem may be caused by the restrictive loop condition, which can be changed to y < 4 to solve.

About the Author

Question Info

Publish Time
2023-02-25 12:03
Update Time
2023-02-25 12:03