How to wait with For Loops?

I’m trying to make a QTE-ish thing. You interchangibly press R or E, and i put it into a for loop 3 times.
This is the code

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Script : MonoBehaviour
{
    private int score =0;
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            Debug.Log("pressed space");
            Method();
        }
    }

    void Method()
    {
        Debug.Log("entered method");
        for (int i = 0;i<3;i++)
        {
            Debug.Log("Entered Loop");
            StartCoroutine(wait());
        }
    }

    IEnumerator wait()
    {
        Debug.Log("Entered Corutine");
        if (score==0)
        {
            yield return new WaitUntil(() => Input.GetKeyDown(KeyCode.R));
            Debug.Log("pressed R");
            score += 1;
        }
        if (score==1)
        {
            yield return new WaitUntil(() => Input.GetKeyDown(KeyCode.E));
            Debug.Log("pressed E");
            score -= 1;
        }
    }
}

From the Devlogs, everything just repeats itself 3 times. Like this
9163358--1274960--upload_2023-7-21_19-33-16.png
Then when I press R, R prints three times back-to-back
How do I stay in one instance of the loop until a key is pressed?

Fighting game control input combos might be one good reference for this stuff.

The coroutines you have above are a little bit entangled… I don’t think you want them that way.

Coroutines in a nutshell:

Splitting up larger tasks in coroutines:

Coroutines are NOT always an appropriate solution: know when to use them!

“Why not simply stop having so many coroutines ffs.” - orionsyndrome on Unity3D forums

Our very own Bunny83 has also provided a Coroutine Crash Course:

https://answers.unity.com/questions/1749615/coroutines-ienumerator-not-working-as-expected.html?childToView=1749714#answer-1749714

1 Like

You need to yield the coroutines if you want to wait for them to finish, which also requires you to be in a coroutine

    IEnumerator Method()
    {
        Debug.Log("entered method");
        for (int i = 0;i<3;i++)
        {
            Debug.Log("Entered Loop");
            yield return StartCoroutine(wait());
        }
    }

and now of course you have to start that as a coroutine

1 Like