0
votes

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?

1
It doesn't change isPlayerTurn, you change isPlayerTurn. The code that changes it is right there in your question. Can you clarify by explaining what behaviour you were expecting and why? - user743382
@hvd The value of isPlayerTurn should still be False after that yield because it's necessary through the ShowPattern() function and should be True only after ShowPattern() finishes executing (on the //etc part). - Jean Catanho
I'm not asking why you want it to be false, I'm asking why you think the current code would keep it false. - user743382
Because I thought isPlayerTurn = true; would execute only after ShowPattern() finished. - Jean Catanho
You can add some identifiers to your Debug.Log calls (something like Debug.Log("Update " + isPlayerTurn) so you know exactly which debug output is which. - Jiri P.

1 Answers

2
votes

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?