- Home /
Wait for button response in coroutine?
I’ve got a colour puzzle-type game and have 2 UI buttons that I’m trying to set up functionality for - a “YES” button and a “NO” button. If the colours match, you need to press the YES button and if they don’t you press the NO button.
Currently, I’m using the On Click function in the inspector for each button. I’ve got a method for the yes button (EvaluateYesResponse) and a separate method for the no button (EvaluateNoResponse). So, for the NO button I've selected the EvaluateNoResponse function, and similarly for the YES button. These methods are currently in a coroutine so that: a new colour is presented, player makes a response by pressing yes or no, a score is awarded, then after 0.5 seconds, the next colour is presented.
At the moment, my button functionality isn’t working even though I’ve made a reference to the buttons and assigned them in the inspector. When I press play, the colours just keep switching without waiting for the player’s response.
I suspect that I'm going wrong by placing the two evaluate methods in the coroutine but I'm not sure where else to call them. Essentially what I am hoping for is to present the colour puzzle, then wait for the player’s response by pressing the yes or no button, then present the next puzzle. Any help with setting up these buttons would be greatly appreciated!!
public class ColourGameManager : MonoBehaviour
{
//reference
ColourLevelManager level;
//game variables
public bool gamePlaying;
//scoring variables
public int currentScore = 0;
public TextMeshProUGUI scoreText;
//feedback variables
public GameObject correctFeedback;
public GameObject incorrectFeedback;
public bool responseMade;
public Button YesButton;
public Button NoButton;
private void Start()
{
StartCoroutine(StimulusRoutine());
gamePlaying = true;
}
IEnumerator StimulusRoutine()
{
while(true)
{
while (gamePlaying == true)
{
GetComponent<ColourLevelManager>().GetNextColour();
EvaluateNoResponse();
EvaluateYesResponse();
yield return new WaitForSeconds(0.5f);
}
yield return new WaitForEndOfFrame();
}
}
//SCORING: award & add points to current score, then display on screen
public void AddToScore()
{
currentScore += level.pointsAwarded;
scoreText.text = currentScore.ToString();
}
//RESPONSE EVALUATION
public void EvaluateNoResponse()
{
responseMade = true;
level = GetComponent<ColourLevelManager>();
if (level.randomTargetColourWord == level.randomStimulusColour)
{
level.correctResponse = false;
}
else if (level.randomTargetColourWord != level.randomStimulusColour)
{
level.correctResponse = true;
AddToScore();
//feedback
}
}
public void EvaluateYesResponse()
{
responseMade = true;
level = GetComponent<ColourLevelManager>();
if (level.randomTargetColourWord == level.randomStimulusColour)
{
level.correctResponse = true;
AddToScore();
//feedback
}
else if (level.randomTargetColourWord != level.randomStimulusColour)
{
level.correctResponse = false;
//feedback
}
}
}
Answer by Bunny83 · Jul 25, 2019 at 03:24 PM
Since this is a quite common issue / task to wait for an UI button press in a coroutine, I just created a custom yield instruction that will handle this for you. I added it to the Unity Wiki: WaitForUIButtons.
edit Since the unity wiki seems to be down for good, here's an archive.org link for the moment.
Here's also a pastebin backup of the script.
You can provide it a list of UI buttons and this class will register temporary callbacks to all those buttons. When one of the buttons is pressed the internal "PressedButton" property will be set to the button that was pressed. So you can simply do:
// from my wiki examples
public Button yesButton;
public Button noButton;
IEnumerator Dialog()
{
// ...
var waitForButton = new WaitForUIButtons(yesButton, noButton);
yield return waitForButton.Reset();
if (waitForButton.PressedButton == yesButton)
{
// yes was pressed
}
else
{
// no was pressed
}
// ...
}
Answer by anjuman · Jul 24, 2019 at 09:45 AM
In your code, the Coroutine is in while loop with a "gamePlaying" true, and as gamePlaying is always true that's why it is not waiting for the input. you can declare another boolean as in "_isWaitOver" and make it true on button click
while (gamePlaying == true)
{
if(_isWaitOver)
GetComponent().GetNextColour();
EvaluateNoResponse();
EvaluateYesResponse();
yield return new WaitForSeconds(0.5f);
}
As you've suggested, I declared another boolean and made it true on button click, but now Unity freezes every time I try to run the game. Could you please help me out with this? Thanks in advance for your help with this!
private void Start()
{
StartCoroutine(StimulusRoutine());
gamePlaying = true;
}
IEnumerator StimulusRoutine()
{
while(true)
{
while (gamePlaying == true)
{
if(response$$anonymous$$ade)
{
GetComponent<ColourLevel$$anonymous$$anager>().GetNextColour();
EvaluateNoResponse();
EvaluateYesResponse();
yield return new WaitForSeconds(1f);
}
}
yield return new WaitForEndOfFrame();
}
}
//RESPONSE EVALUATION
public void EvaluateNoResponse()
{
response$$anonymous$$ade = true;
level = GetComponent<ColourLevel$$anonymous$$anager>();
if (level.randomTargetColourWord == level.randomStimulusColour)
{
level.correctResponse = false;
}
else if (level.randomTargetColourWord != level.randomStimulusColour)
{
level.correctResponse = true;
AddToScore();
//feedback
}
}
public void EvaluateYesResponse()
{
response$$anonymous$$ade = true;
level = GetComponent<ColourLevel$$anonymous$$anager>();
if (level.randomTargetColourWord == level.randomStimulusColour)
{
level.correctResponse = true;
AddToScore();
//feedback
}
else if (level.randomTargetColourWord != level.randomStimulusColour)
{
level.correctResponse = false;
//feedback
}
}
There is a slight logic issue, unity freezes because of while(true) loop with WaitForEndOfFrame(), meaning Coroutine is iterating itself every end of frame i.e. if there are 20 frames per second, so much resource consumption.
you can test yourself by commenting this while(true) loop out or return it WaitForSeconds(time);// time = 10 seconds for testing,
ins$$anonymous$$d of WaitForEndOfFrame();
You almost never need or should use "WaitForEndOfFrame" this is only required for some really special cases when you want to render something on top of everything at the end of a frame. If you just want to wait one frame you should simply yield "null". Creating a WaitForEndOfFrame object each frame will just produce garbage. Also like anjuman said: never have an endless running while loop without at least one yield statement in it. Otherwise, depending on your logic, you can never exit this while loop and your whole application will freeze.
@anjuman I wouldn't recommend using InvokeRepeating or WaitForSeconds in such a case. Both will just lead to an unresponsive user experience. The user presses the button but it would take x amount of time until your game actually reacts to the input. There's really no issue checking this every frame. However as i said you should just use yield return null;
when you want to wait for the next frame.
Also I would avoid having too many nested loops. This would be a lot clearer:
IEnumerator StimulusRoutine()
{
ColourLevel$$anonymous$$anager clm = GetComponent<ColourLevel$$anonymous$$anager>()
while(true)
{
// wait here until "gamePlaying" becomes true
while (!gamePlaying)
yield return null;
if(response$$anonymous$$ade)
{
clm.GetNextColour();
EvaluateNoResponse();
EvaluateYesResponse();
yield return new WaitForSeconds(1f);
}
yield return null;
}
}
Ins$$anonymous$$d of that extra waiting while loop you could also just do:
if(gamePlaying && response$$anonymous$$ade)
Which would have the exact same effect in this case. Though there might be other situations where you might want to use the first approach. In long coroutines having small well defined waiting points often helps with the readability. Because as the execution reaches that waiting while loop the only things relevant at this point are the conditions in that nested while loop, nothing else. It also allows you to use different wait times for different parts.
Finally keep in $$anonymous$$d that unlike some other yield instructions (those derived from CustomYieldInstruction), the WaitForSeconds instance can actually be cached and reused if the time doesn't change. Note that WaitForSecondsRealtime can not be cached as it's actually a custom yield instruction and has internal state. WaitForSeconds is a built-in feature where the actual waiting happens directly in the coroutine scheduler and unity just reads the delay value out of that WaitForSeconds instance.
Your answer
Follow this Question
Related Questions
Using a coroutine to wait for a button press? 1 Answer
How can I make GUI button send an input message when I press it? 0 Answers
Input.getTouch() vs checking if button is clicked 1 Answer
How do I detect touch on another object and check by tag/name? 1 Answer
Why does the keyboard control what button is selected? 2 Answers