Reputation: 326
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?
Upvotes: 0
Views: 1527
Reputation: 181
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?
Upvotes: 2