【问题标题】:Why my foreach loop executes in this order?为什么我的 foreach 循环按此顺序执行?
【发布时间】:2018-09-17 22:44:46
【问题描述】:

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

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

也许这是 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);
}

【问题讨论】:

  • immic 模仿了 1973 年的原始 Simon 游戏 - 给它一些信任! :)

标签: c# unity3d coroutine


【解决方案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());,因为它现在是一个协程函数。

【讨论】:

    猜你喜欢
    • 2020-01-01
    • 2020-08-14
    • 2019-07-05
    • 2013-01-04
    • 1970-01-01
    • 2015-10-25
    • 2018-03-24
    • 2017-01-20
    • 1970-01-01
    相关资源
    最近更新 更多