(C#) Execute script when button is held for 'x' seconds

Hi everyone,

Trying to set up a countdown timer to execute a block of code after a button is held for ‘x’ number of seconds. Here’s where I’m at…

float inputTimer;
bool isUI1 = true;

void Update () { progressUI1(); }

public void progressUI1()
{

        if (isUI1 == true)
        {

            inputTimer = 2;

            if (Input.GetKey(KeyCode.Return))
            {

                inputTimer -= Time.deltaTime;

                if (inputTimer <= 0)
                {
                    // do stuff
                }

            }

        }

    }

I may need to use a ‘for’ loop, not sure. Any help would be greatly appreciated. :smiley:

Jonathan

Hi;
u need some thing like Gun Reload Time;
u need to wait for some seconds then execute some code;

    float WaitingTime = 10f;
 

    void Update()
    {

        if (isUI1 == true)
        {

            if (Input.GetKey(KeyCode.Return) && WaitingTime == false)
            {
                WaitingTime = true;
                StartCoroutine(Reload(WaitingTime));

            }

        }

    }
        IEnumerator Reload(float TimeToWait)
    {
       
        yield return new WaitForSeconds(TimeToWait);
        //Do Stuff
        WaitingTime = false;
    }

If you want it to run your code after n seconds of possibly discontinued key press, your code is already fine.
If you want it to reset every time you release before the countdown has come to zero, you would use something like this :

bool longKeyPressed;
public void progressUI1()
{
    if (isUI1 == true)
    { 
        inputTimer = 2; 
        if (Input.GetKey(KeyCode.Return))
        {
            inputTimer -= Time.deltaTime; 
            if (inputTimer <= 0)
            {
                // do stuff
                // possibly use a coroutine like suggested by @Cuttlas-U if you need your code to run over several frames
                StartCoroutine (DoAfterLongKeyPress ());
                // or simply turn a bool variable to true and use it to filter some later code to run in Update
                longKeyPressed = true;
            }
        }
        if (Input.GetKeyUp(KeyCode.Return))
        {
            inputTimer = 2; // timer reset on release
        }
        if (longKeyPressed)
        {
            // do stuff
            longKeyPressed = false;
        }
    }
}
IEnumerator DoAfterLongKeyPress ()
{
    // do stuff
    yield return false;
}