What I am trying to understand and learn here is a very basic thing: what is the most general and most polished way to properly differentiate single-clicks and double-clicks for the 3 main mouse buttons in Unity, using C#?
My emphasis on the word properly is not for nothing. Although I was surprised that this seems to have never been asked in this website before, of course I have searched and found numerous similar questions on Unity's forums and Unity's own question-answer pages. However, as it is often the case with answers posted in these resources, they all seemed to be either plain wrong or at least a bit too amateurish.
Let me explain. Proposed solutions always had either of the two approaches and their corresponding flaws:
- every time a click happens, calculate time delta since last click and if it was smaller than a given threshold, a double click would be detected. However, this solution results in that a quick single click is detected before the double-click is detected, which is undesirable in most situations because then it activates both single and double click actions.
Rough example:
float dclick_threshold = 0.25f;
double timerdclick = 0;
if (Input.GetMouseButtonDown(0)
{
if (Time.time - timerdclick) > dclick_threshold)
{
Debug.Log("single click");
//call the SingleClick() function, not shown
} else {
Debug.Log("double click");
//call the DoubleClick() function, not shown
}
timerdclick = Time.time;
}
- set a wait-for delay for the single-click to be activated, which means, at every click, only activate single click actions if the time delay since last click is above a given threshold. However, this gives sluggish results, since a waiting before it is possible to notice the waiting before single-clicks are detected. Worse than that, this kind of solution suffers from discrepancies across machines, since it does not take into account how slow or how fast is the user's double-click speed setting at the OS level.
Rough example:
float one_click = false;
float dclick_threshold = 0.25f;
double timerdclick = 0;
if (one_click && ((Time.time - timerdclick) > dclick_threshold))
{
Debug.Log("single click");
//call the SingleClick() function, not shown
one_click = false;
}
if (Input.GetMouseButtonDown(0))
{
if (!one_click)
{
dclick = -1;
timerdclick = Time.time;
one_click = true;
}
else if (one_click && ((Time.time - timerdclick) < dclick_threshold))
{
Debug.Log("double click");
//call the DoubleClick() function, not shown
one_click = false;
}
}
Therefore, my questions becomes the following. Is there a more polished and reliable way of detecting double clicks in Unity using C#, other than these solutions, and one that handles the problems aforementioned?
No comments:
Post a Comment