简体   繁体   中英

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM