Why does the coroutine changes the value of a variable?
In Unity C#, I'm using a coroutine to display a simple pattern on the screen after x seconds using the line "yield return new WaitForSeconds(1.5f)" but after it's first called, it changes isPlayerTurn from false to 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
}
The output of the logs are
False
False
True
Is there a reason for this behavior or is it a logic error?
As hvd wrote you set isPlayerTurn to true. When you start coroutine current method is not stopped, but it executes next statement in paralel to method in coroutine.
Here you cen see example how coroutine is working in unity: The Unity3D StartCoroutine calls a function, when does that function return?
链接地址: http://www.djcxy.com/p/53174.html上一篇: Unity2D:每按一次按钮就开始一个新的协同程序
下一篇: 为什么协程会改变变量的值?