So Im trying to implement some double click features into a project, and Im having a little difficulty. What Ive been trying so far is to have a timer start when the user clicks, then if the second click comes before the end of the timer itll register a double click. But havent been able to get it to work right yet. Anyone know how to do this? Seems like it should be pretty simple.
You could use Event.current.clickCount in OnGUI, which has the added benefit of using the user’s OS settings for double-click speed.
–Eric
Got it working this morning.
using UnityEngine;
using System.Collections;
public class DoubleClick : MonoBehaviour {
#region Class Variables
public float doubleClicklag = 0.5f;
public float doubleClickTime;
public bool singleClick = false;
#endregion
void Start ()
{
}
void Update ()
{
if(singleClick Input.GetMouseButtonUp(0))
{
ActivateDoubleClick();
}
if(Input.GetMouseButtonUp(0))
{
singleClick = true;
doubleClickTime = Time.time + doubleClicklag;
}
if(Time.time >= doubleClickTime)
{
singleClick = false;
}
}
void ActivateDoubleClick ()
{
Debug.Log ("Double Click Activated");
}
}
Now that Ive got it working it seems so damn simple. To anyone else that might want to use this. The amount of time allow for it to recognize a double click is set by the doubleClickLag variable. Lowering it will tighten up the time, raising it will allow for a slower double click. Then any code you want to activate when you double click should be inserted into the ActivateDoubleClick function.
The doubleClickTime and singleClick variables can also be set to private to clear up the inspector, I just had them public for testing purposes.
Code variation on double click for those who are not satisfied by Event.clickCount, put the script in high priority (to be executed first):
public float _doubleClickDelay = 0.5f;
public bool _leftDoubleClick;
private float _doubleClickTimeLimit;
void Start () {
_leftDoubleClick = false;
_doubleClickTimeLimit = 0.0f;
}
void Update () {
if (Input.GetMouseButtonUp(0)) {
if (Time.time < _doubleClickTimeLimit) {
_leftDoubleClick = true;
_doubleClickTimeLimit = 0.0f;
}
else {
_leftDoubleClick = false;
_doubleClickTimeLimit = Time.time + _doubleClickDelay;
}
}
else {
_leftDoubleClick = false;
}
}