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

时间:2018-09-17 22:44:47

标签: c# unity3d coroutine

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

这里的问题是,所有代码都能完美运行,但是上面有详细说明,
 游戏按以下顺序运行: How it runs ,(如您所见,一起),但是我需要它像这样运行: enter image description here

这可能是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);
}

1 个答案:

答案 0 :(得分:1)

如果希望for循环中的每个代码一个一个地执行,则必须使其等待下一个循环之前,该for循环中调用的协程函数完成。也使Randomizer()函数成为协程,然后使用OneMethod()

产生TwoMethod()ThreeMethod()yield return StartCoroutine(YourMEthod()).函数调用
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());,因为它现在是协程函数。