0
\$\begingroup\$

When I hold down a button by mouse for 5 seconds, print a message. How to do this ? I wrote this script but is not working. I don't know if there other methods.

Public float clock;
Public Button out;

public void quit_out_mouse() {
    clock = Time.time;
    if(Time.time - clock > 3.0f )       {
        Debug.Log (" gone !! ");
    }

   }
\$\endgroup\$
2
\$\begingroup\$

I don't think the code of @virtouso would work : It's not frame independent and if you hold the button down for 2 seconds, release it, the timer will not reset

public float duration = 6 ;
private float timer = 0;
private bool waitingButtonUp = false ;

private void Update()
{
    // Use waiting button up if you don't want the function to be called every 6 seconds
    // but you want the user to release the mouse button before being able to call
    // the function after pressing the button again
    if( Input.GetMouseButton(0) && !waitingButtonUp )
    {
        timer += Time.deltaTime ;
    }
    else // Do not forget to reset timer when the button is not pressed anymore
    {
        timer = 0 ;
        waitingButtonUp = false;
    }

    if( timer > duration )
    {
        DoSomething();
        waitingButtonUp = true ;
        timer = 0 ;
    }
}

private void DoSomething()
{

}
\$\endgroup\$
1
  • \$\begingroup\$ Yes, you right. I edited his code and solve it. Thank you Hellium for the new script. \$\endgroup\$ – user43474 Jan 21 '17 at 19:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.