Determining the duration of a mouse click?

Hi,

Is there a way of determining the amount of time the mouse button has been held down for?

Many thanks,

Jaz

remember the time.time when onmousedown has been registered and in onmouseup subtract the stored value from the current time.time.

there are Input.GetMouseButtonUp and Input.GetMouseButtonDown… so you could log the time at each and work out the difference.

Many thanks guys for taking the time to reply.
I’d arrived at pretty much the same thing whilst waiting.
Here’s my script in case its of use to anyone :

using UnityEngine;
using System.Collections;

public class ButtonClickDuration : MonoBehaviour {

float timeCurrent;
float timeAtButtonDown ;
float timeAtButtonUp ;
float timeButtonHeld = 0 ;
bool draggable = false;

void Start (){

}

void Update (){

timeCurrent = Time.fixedTime;

}

void OnMouseDown(){
timeAtButtonDown = timeCurrent;
Debug.Log (“Time button pressed” + timeAtButtonDown);
}

void OnMouseUp (){
timeAtButtonUp = timeCurrent;
Debug.Log (“Time button released” + timeAtButtonUp);

timeButtonHeld = (timeAtButtonUp - timeAtButtonDown);
Debug.Log ("TimeButtonHeld = " + timeButtonHeld);

if (timeButtonHeld > 2)
{
Debug.Log (“Yeah, you held the mouse for longer than 2 secs!!”);
}
}
}

1 Like