Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
12 Jun 22 - 14 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
1
Question by lalalanni · Jul 24, 2019 at 04:23 AM · inputbuttoncoroutine

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
         }
     }
  }
Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

2 Replies

· Add your reply
  • Sort: 
avatar image
2
Best Answer

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
     }
     // ...
 }


Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image I_Am_Err00r · Jul 25, 2019 at 03:31 PM 0
Share

Such a simple solution, thanks man!

avatar image lalalanni · Jul 25, 2019 at 08:57 PM 0
Share

Thank you!!

avatar image
1

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); 
       }







Comment
Add comment · Show 5 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image lalalanni · Jul 24, 2019 at 09:36 PM 0
Share

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
         }
     }
avatar image anjuman lalalanni · Jul 24, 2019 at 10:21 PM 0
Share

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.

avatar image anjuman anjuman · Jul 24, 2019 at 10:24 PM 0
Share

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();

Show more comments
avatar image Bunny83 lalalanni · Jul 25, 2019 at 01:12 PM 1
Share

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

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

155 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Using a coroutine to wait for a button press? 1 Answer

Help In Making a SphereCast for 3D Tire! Working RayCast Script included! 0 Answers

Is there any function to check how long a button is pressed? 2 Answers

Show GUI.Button press state by keyboard input? 1 Answer

Catch all inputs on a button before selection change 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges