Author Topic: How long was a button pressed?  (Read 1497 times)

BehindTheStone

  • Full Member
  • ***
  • Thank You
  • -Given: 0
  • -Receive: 0
  • Posts: 135
    • View Profile
How long was a button pressed?
« on: March 11, 2014, 11:20:48 AM »
Hey there!

Is there a nice way to measure the time while pressing a button?
Meaning: When I press and hold a button a "timer" should go off and if it the button is pressed long enough something happens.

I searched the forums already and only got some older postings where recording the time in OnPress and checking it in Update was suggested. A legit and good idea, but here's the thing:

When the button is pressed long enough there should "popup" another GUI-Window (Widget, Sprite etc.) with a label asking the Player something specific.
I wanted to achieve this with Coroutines and NGUI-Tween-Events. Coroutines don't work properly in Update() and I don't want to add Events every frame in Update() while the "timer" fulfills the condition.


  1. void OnPress(bool pressed)
  2. {
  3. if(pressed)
  4. {
  5. // I know this won't work, but I add it anyways, so you get my idea:
  6.  
  7. timer += Time.deltatime;
  8.  
  9. if(timer >= x)
  10. {
  11. // Start Coroutines
  12. // Do cool Eventstuff
  13. }
  14. }
  15. }


Any suggestions? :)

ArenMook

  • Administrator
  • Hero Member
  • *****
  • Thank You
  • -Given: 337
  • -Receive: 1171
  • Posts: 22,128
  • Toronto, Canada
    • View Profile
Re: How long was a button pressed?
« Reply #1 on: March 11, 2014, 04:49:52 PM »
  1. void OnPress (bool pressed)
  2. {
  3.     if (pressed) StartCoroutine(YourCheckFunction());
  4.     else StopAllCoroutines();
  5. }
  6.  
  7. IEnumerator YourCheckFunction()
  8. {
  9.     yield return new WaitForSeconds(1f);
  10.     // Do stuff
  11. }

BehindTheStone

  • Full Member
  • ***
  • Thank You
  • -Given: 0
  • -Receive: 0
  • Posts: 135
    • View Profile
Re: How long was a button pressed?
« Reply #2 on: March 11, 2014, 05:03:54 PM »
Damn. Of course!