【问题标题】:Why does the coroutine changes the value of a variable?为什么协程会改变变量的值?
【发布时间】:2016-06-20 16:32:30
【问题描述】:

在 Unity C# 中,我使用协程在 x 秒后使用“yield return new WaitForSeconds(1.5f)”行在屏幕上显示一个简单模式,但在第一次调用后,它会将 isPlayerTurn 从 false 更改为 true .

     void Update () {
        if (!isPlayerTurn) {
            pattern.Add (Random.Range (1, 5));
            Debug.Log (isPlayerTurn);
            StartCoroutine(ShowPattern());
            isPlayerTurn = true;

        }

        pointGUI.GetComponent<UnityEngine.UI.Text> ().text = "Points: " + playerPoints;
    }

    private IEnumerator ShowPattern() {
        Debug.Log (isPlayerTurn);
        yield return new WaitForSeconds (1.5f);
        Debug.Log (isPlayerTurn);

        // etc
    }

日志的输出是

False
False
True

这种行为是有原因的还是逻辑错误?

【问题讨论】:

  • 不会改变isPlayerTurn会改变isPlayerTurn。更改它的代码就在您的问题中。您能否通过解释您所期望的行为以及原因来澄清?
  • @hvd 在该 yield 之后,isPlayerTurn 的值仍应为 False,因为它是通过 ShowPattern() 函数所必需的,并且仅在 ShowPattern() 完成执行后才应为 True(在//等部分)。
  • 我不是在问你为什么希望它是 false,我是在问你为什么认为当前的代码会保留它 false
  • 因为我认为isPlayerTurn = true; 只会在ShowPattern() 完成后执行。
  • 您可以在您的Debug.Log 调用中添加一些标识符(类似于Debug.Log("Update " + isPlayerTurn),这样您就可以准确地知道哪个调试输出是哪个。

标签: c# unity3d


【解决方案1】:

正如 hvd 所写,您将 isPlayerTurn 设置为 true。 当您启动协程时,当前方法不会停止,而是并行执行协程中的方法的下一条语句。

在这里,您可以看到协程如何统一工作的示例:The Unity3D StartCoroutine calls a function, when does that function return?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-25
    • 1970-01-01
    • 1970-01-01
    • 2022-07-04
    • 1970-01-01
    • 2014-11-15
    • 2015-01-07
    • 2013-10-29
    相关资源
    最近更新 更多