首页 > 解决方案 > Unity - 一切都冻结在“ yield return new WaitForSeconds(); ”?

问题描述

好的!我在这个场景中的所有代码都在一个脚本和一个管理器对象中。所有这些都是大约 700 行。所以我不能把它放在这里。我测试了不同的东西:

他们都没有解决问题。然后我更改了我怀疑会导致问题的代码的某些部分。(他们都没有解决解决方案)。然后我开始把 Debug.Log()s 到处放。所以我找到了它冻结的地方。

这是代码:

    IEnumerator ShowSigns(int Button1State, int EqualState, int Button2State)
    {

        Debug.Log("ShowSigns");
        if (Button1State == 1)
        {
            OperationOneCorrectSign.GetComponent<CanvasGroup>().alpha = 1;
        }
        else if (Button1State == 2)
        {
            OperationOneIncorrectSign.GetComponent<CanvasGroup>().alpha = 1;
        }
        if (EqualState == 1)
        {
            EqualCorrectSign.GetComponent<CanvasGroup>().alpha = 1;
        }
        else if (EqualState == 2)
        {
            EqualIncorrectSign.GetComponent<CanvasGroup>().alpha = 1;
        }
        if (Button2State == 1)
        {
            OperationTwoCorrectSign.GetComponent<CanvasGroup>().alpha = 1;
        }
        else if (Button2State == 2)
        {
            OperationTwoIncorrectSign.GetComponent<CanvasGroup>().alpha = 1;
        }

        Debug.Log("BeforeWaiting");
        yield return new WaitForSeconds(0.3f);

        Debug.Log("AfterWaiting");
        OperationOneCorrectSign.GetComponent<CanvasGroup>().alpha = 0;
        OperationOneIncorrectSign.GetComponent<CanvasGroup>().alpha = 0;
        EqualCorrectSign.GetComponent<CanvasGroup>().alpha = 0;
        EqualIncorrectSign.GetComponent<CanvasGroup>().alpha = 0;
        OperationTwoCorrectSign.GetComponent<CanvasGroup>().alpha = 0;
        OperationTwoIncorrectSign.GetComponent<CanvasGroup>().alpha = 0;
        state = GameState.CreateNewProblem;

        Debug.Log("EndSigns");
    }

我发现它冻结了:

        yield return new WaitForSeconds(0.3f);

很奇怪!!!

这是游戏的图片。

在此处输入图像描述 该游戏是一个简单的游戏,显示 2 个数学短语,玩家应该选择更大或相等。逻辑是这样的:

这个逻辑一遍又一遍地重复,直到时间达到零。任何正确和错误的答案都会使“步长”变量增加和减少 1。变量 level = steps/10 决定了短语的难度。

游戏在 %98 点击 On 按钮上正常运行。但通常,它会在第 20 步之后冻结。在 21、23、27、34 ......非常随机。但总是在 20 岁之后,并且有一段时间没有冻结,直到时间结束。并且总是在收益回报之前。完全在同一行。

我阅读了很多问题和答案,但没有一个是有帮助的。我没有while循环,没有while(true),只要我知道并检查我的代码没有无限循环,在StopAllCoroutines上......什么都没有。我坚持了2天。谢谢大家的帮助。

哦,这是代码文件

标签: unity3dfreezecoroutine

解决方案


冻结的原因是Random.Range用于控制问题中链接while的代码中的循环。在不使用循环的情况下获取随机数的一种方法是将它们生成到然后删除您使用的每一个。这应该可以防止冻结 Unity。whileListRandom.Range


推荐阅读