Unity2D: StartCoroutine to however many times a button was pressed.

Hi, is there a way to make Coroutine start to however many times the button was pressed. I made a script to check however many times a button was pressed, but I don’t know how to StartCoroutine to buttonCount ++. Is it possible?

public int buttonCount = 0;

public void Check() {
	buttonCount ++;
}

This is what I’m using StartCoroutine for:

public GameObject LeftUp, RightUp, LeftDown, RightDown, ForceSphere;
public int buttonCount = 0;

public void Check() {
	buttonCount ++;
}

public void ActivateForceField ()
{
		StartCoroutine (CreateForceField ()); 
		forceActive = true; 
}

IEnumerator CreateForceField ()
{
	LeftUp.SetActive (true);
	RightUp.SetActive (true);
	yield return new WaitForSeconds (1.0f);
	LeftDown.SetActive (true);
	RightDown.SetActive (true);
	yield return new WaitForSeconds (1.0f);
	LeftUp.SetActive (false);
	RightUp.SetActive (false);
	yield return new WaitForSeconds (1.0f);
	LeftDown.SetActive (false);
	RightDown.SetActive (false);
	//yield return new WaitForSeconds (1.0f);
	ForceSphere.SetActive (true);
	yield return new WaitForSeconds (10.0f);
	ForceSphere.SetActive (false);

	forceActive = false;
}

I tried putting Check(); in my IEnumerator at the beginning but it didn’t work. Thank you :slight_smile:

Try this approach:
Add a global variable to track how many times the coroutine started:

int timesActivated =  0;

and each time you start the coroutine increment this value by 1. When this value becomes equal to the value of buttonCount, you need to stop calling the coroutine. The CreateForceField code:

IEnumerator CreateForceField()
    {

        if(timesActivated < buttonCount)
        {
            timesActivated++;

            //the rest of your code in the coroutine

            StartCoroutine(CreateForceField());
        }
    }