Coroutine caller function doesn't wait

Hi, I am writing the following code within a MonoBehaviour class:
Under a certain condition, I want to activate a button, and wait until the player press this button. Only then I want to move to next phase of the game.

private void CallingFunc()
{
	// do something

	if(condition)
	{
		StartCoroutine(CoroutineFunctionWrapper());
	}

	// Do more staff

}

private IEnumerator CoroutineFunctionWrapper() 
{
	yield return StartCoroutine(CoroutineFunction());
}

private IEnumerator CoroutineFunction()
{
	// isButtonSelected is a member of the class, 
	// which will be set to true when the user hit a button
	isButtonSelected = false; 
	SetButtonActive(true); // Set this button as active, show it on screen
	
	yield return StartCoroutine(WaitForButtonSelected());
	
	isButtonSelected = false;
}

private IEnumerator WaitForButtonSelected()
{
	while(isButtonSelected == false)
	{
		yield return new WaitForSeconds(1.1f);
	}
}

But I see the CallingFunc continues and does not wait for the end of the coroutine.
During my tries, I added the CoroutineFunctionWrapper - it doesn’t work with or without it.
I also tried to change CallingFunc to be a coroutine, but it also doesn’t change anything. (Bottom line is that the game continues before the button was pressed by the player.

Any suggestions…?

Thanks!

Please notice that "button" is not a GUI element, but a GameObject.

I update my answer with your last comment

1 Answer

1

Wowowow what are you doing? you starting 3 Coroutines just to detect if button was pressed?
im sure there is much elegant way of detecting a button action

something like:

OnGUI()
{
   if (GUI.Button(new Rect(10, 70, 50, 30), "Click"))
   {
            Debug.Log("User Clicked the button");
   }
}

After you add new comment that Button is GO and not GUI it is even more simpler
in your last Coroutine you do:

while(isButtonSelected == false)
{
   yield return new WaitForSeconds(1.1f);
}

instead of doing so, why dont you move it to Update()?

Update(){

    if(isButtonSelected == true) //or even simplier: if(isButtonSelected)
    {
       //do the stuf you want to do if user select it
    }
    else
    {
        //do nothing, in other words you dont need else statement
    }

}

Thanks a lot for your quick response. I can indeed proceed my actions in Update, but in general - I would like to understand why calling to the coroutine didn't make the CallingFunc to "wait" until it finishes?

Because it is not a "wait" condition, it is something to be executed in parallel. Executor doesn't stop at that point, it keep going to execute next stuff and come back to the place "yield" over and over again to check if it was finished and in maintime executing another code while "yield" condition is not finished