Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Voting for the Unity Awards are OPEN! We’re looking to celebrate creators across games, industry, film, and many more categories. Cast your vote now for all categories
    Dismiss Notice
  3. Dismiss Notice

How to add delay on button press

Discussion in 'UGUI & TextMesh Pro' started by jacksonbarnes, Jul 15, 2018.

  1. jacksonbarnes

    jacksonbarnes

    Joined:
    Sep 13, 2017
    Posts:
    17
    How do I add a delay on a button press? Hit a button to fast breaks some of my UI how do you have a delay on a button so you can only click it every like .5 seconds etc...
     
  2. sebastiansgames

    sebastiansgames

    Joined:
    Mar 25, 2014
    Posts:
    114
    Set up a bool ‘wasPressed’ or something and check for it when the button is pressed. If false, swap to true, execute your button instructions, then call a coroutine to swap the flag back to false after .5 seconds. You might want to think about initializing the flag to false at certain key moments (ie start new level etc) if the coroutine can possibly get interrupted.
     
    jbarnes2018 likes this.
  3. Peter77

    Peter77

    QA Jesus

    Joined:
    Jun 12, 2013
    Posts:
    6,419
    Why not using a float and the current time only? It should not require a coroutine if you just want to ignore the press.
    Code (CSharp):
    1. float m_LastPressTime;
    2. float m_PressDelay = 0.5f;
    3.  
    4. void OnButtonPress()
    5. {
    6.     if (m_LastPressTime + m_PressDelay > Time.unscaledTime)
    7.         return;
    8.     m_LastPressTime = Time.unscaledTime;
    9.  
    10.     Debug.Log("OnButtonPress);
    11. }
     
    scottygavin and jbarnes2018 like this.
  4. burgerandfries43

    burgerandfries43

    Joined:
    Jan 23, 2021
    Posts:
    8
    just added a quick little grammar thing if people need it