为什么我的 foreach 循环按这个顺序执行?

Why my foreach loop executes in this order?

我有一个Unity3D游戏,在这个游戏中有一个类似iMimic的游戏。

这里的问题是,所有代码都能完美运行,但它有一个细节,
游戏顺序 运行s: ,(如您所见,全部在一起),但我需要它 运行 像这样:

也许这是 foeach 循环或 IEnumerators 的细节?

 void Randomizer()
    {
        PreList = PreList.OrderBy(C => Rnd.Next()).ToArray();
        foreach (var item in PreList)
        {
            Debug.Log(item.ToString());
            if (item == 1)
            {
                StartCoroutine(OneMethod());
            }
            if (item == 2)
            {
                StartCoroutine(TwoMethod());

            }
        if (item == 3)
        {
            StartCoroutine(ThreeMethod());

        }
}
 IEnumerator OneMethod()
 {
    ButtonList.Add(1);
    GameObject.Find("Red").GetComponent<Image>().color = Color.gray;
    //Sound
    yield return new WaitForSeconds(1);
    GameObject.Find("Red").GetComponent<Image>().color = Color.white;
    Debug.Log("Everyone");
    yield return new WaitForSeconds(1);
}
IEnumerator TwoMethod()
{
    ButtonList.Add(2);
    GameObject.Find("Blue").GetComponent<Image>().color = Color.gray;
    yield return new WaitForSeconds(1);
    GameObject.Find("Blue").GetComponent<Image>().color = Color.white;
    Debug.Log("Everyone");
    yield return new WaitForSeconds(1);
}
IEnumerator ThreeMethod()
{
    ButtonList.Add(3);
    GameObject.Find("Green").GetComponent<Image>().color = Color.gray;
    yield return new WaitForSeconds(1);
    GameObject.Find("Green").GetComponent<Image>().color = Color.white;
    Debug.Log("Everyone");
    yield return new WaitForSeconds(1);
}

如果想让for循环中的每段代码都一个一个执行,就得让它等待那个for循环中调用的协程函数执行完,然后再进行下一个循环。使 Randomizer() 函数也成为协程,然后使用 yield return StartCoroutine(YourMEthod()).

产生 OneMethod()TwoMethod()ThreeMethod() 函数调用
IEnumerator Randomizer()
{
    PreList = PreList.OrderBy(C => Rnd.Next()).ToArray();
    foreach (var item in PreList)
    {
        Debug.Log(item.ToString());
        if (item == 1)
        {
            yield return StartCoroutine(OneMethod());
        }
        if (item == 2)
        {
            yield return StartCoroutine(TwoMethod());

        }
        if (item == 3)
        {
            yield return StartCoroutine(ThreeMethod());
        }
    }
}

最后,您必须更改呼叫方式 Randomizer()。它必须从 Randomizer(); 更改为 StartCoroutine(Randomizer()); 因为它现在是协程函数。