Home > Mobile >  How to do a "hold down E key for 3 seconds" in Unity
How to do a "hold down E key for 3 seconds" in Unity

Time:10-21

I have tried to make the following script:

float timer=0;
float timerB=0;

if ( Input.GetButtonDown ( "Fire2" ) )
{
    timer = Time.time;
    Debug.Log ( timer );
}

if ( Input.GetButtonUp ( "Fire2" ) )
{
    timerB = Time.time;
    Debug.Log ( timerB   " ESPACIOSSS "   timer );
    if ( timerB - timer >= 3 )
    {
        timer = 0;
        timerB = 0;
        Debug.Log ( "CONSEGUIDOOOOOOOOOOOOOOOOOOOOOOOOOO" );
    }
}

don't pay attention to the labels xd, the thing is that it doesn't work and trying to debug the code by putting logs Unity tells me that timerB has the value of time BUT timer is 0, then I tried to do things with coroutines but I don't understand anything.

First of all, thank you very much for reading the text, and if you are going to answer and you are Spanish-speaking I would appreciate if you answer me in Spanish, otherwise it doesn't matter.

CodePudding user response:

Please post the full code. Your problem is most likely that you declare your variables as local variables within a method. For example:

private void Update(){
    float timer=0;//every loop new variables are made and set to 0
    float timerB=0;
    ...
    //at the end of the loop, these variables are destroyed
}

Instead, declare them outside of any methods (but inside the class):

float timer=0;//variable is only made once and isn't destroyed
float timerB=0;
private void Update(){
    ...
}

This will allow the variables to retain their values between loops. Read up on local variables, global variables and the call stack

  • Related