- Home /
How to detect double click in c#?
I was create code that find click and hold click, and I wanna add double click where there is no action, the movespeed still 3.
This is my code:
private float t0, moveSpeed;
private bool longClick, shortClick;
void Start ()
{ t0 = 0f; longClick = false; shortClick = false; }
void update()
{
// how and where add the code for detect double click?
if (Input.GetMouseButtonDown (0))
{
t0 = 0; t0 += Time.deltaTime;
longClick = false; shortClick = false;
moveSpeed = 0;
}
if (Input.GetMouseButton(0))
{
t0 += Time.deltaTime;
if (t0 < 0.2)
{ moveSpeed = 15;longClick = false; shortClick = true; } // this is click!
if (t0 > 0.2)
{ moveSpeed = 3; longClick = true; shortClick = false; } // this is hold click!
}
if (Input.GetMouseButtonUp(0))
{
if (longClick == true)
{ moveSpeed = 3; }
else if (shortClick == true)
{ moveSpeed = 3; }
}
}
Answer by MANDAL0R3 · May 10, 2015 at 10:20 PM
I just created this today. Just Create a new instance of the class then use the Method DoubleClick() inside of a Input.GetMouseDown() and if you double click it will return true, else it will return false.
using UnityEngine;
using System.Collections.Generic;
using System;
public class ClickManager
{
public const double MAX_TIME_TO_CLICK = 0.5;
public const double MIN_TIME_TO_CLICK = 0.05;
public bool IsDebug { get; set; }
private TimeSpan maxDuration = TimeSpan.FromSeconds(MAX_TIME_TO_CLICK);
private TimeSpan minDuration = TimeSpan.FromSeconds(MIN_TIME_TO_CLICK);
private System.Diagnostics.Stopwatch timer;
private bool ClickedOnce = false;
public bool DoubleClick()
{
if (!ClickedOnce)
{
timer = System.Diagnostics.Stopwatch.StartNew();
ClickedOnce = true;
}
if (ClickedOnce)
{
if (timer.Elapsed > minDuration && timer.Elapsed < maxDuration)
{
if (IsDebug)
Debug.Log("Double Click");
ClickedOnce = false;
return true;
}
else if (timer.Elapsed > maxDuration)
{
ClickedOnce = false;
if (IsDebug)
Debug.Log("Time out");
return false;
}
}
return false;
}
}
EDIT: I'm going to keep the old code up in case anyone wants it. This is my new version for double clicking.
using UnityEngine;
[System.Serializable]
public class ClickManager
{
//properties
public float MaxTimeToClick { get { return _maxTimeToClick; } set { _maxTimeToClick = value; } }
public float MinTimeToClick { get { return _minTimeToClick; } set { _minTimeToClick = value; } }
public bool IsDebug { get { return _Isdebug; } set { _Isdebug = value; } }
//property variables
private float _maxTimeToClick = 0.60f;
private float _minTimeToClick = 0.05f;
private bool _Isdebug = false;
//private variables to keep track
private float _minCurrentTime;
private float _maxCurrentTime;
public bool DoubleClick()
{
if (Time.time >= _minCurrentTime && Time.time <= _maxCurrentTime)
{
if (_Isdebug)
Debug.Log("Double Click");
_minCurrentTime = 0;
_maxCurrentTime = 0;
return true;
}
_minCurrentTime = Time.time + MinTimeToClick; _maxCurrentTime = Time.time + MaxTimeToClick;
return false;
}
}
Great answer! You're missing something though, you need to restart the timer when you time out. So if the user does something like Click --> Wait a few sec --> Click Click, they don't get stuck in a "Time Out Loop". I just replaced it with:
else if (timer.Elapsed > maxDuration)
{
timer = System.Diagnostics.Stopwatch.StartNew();
ClickedOnce = true;
if (IsDebug)
Debug.Log("Time out");
return false;
}
Answer by dilippatil · Jul 11, 2017 at 01:24 PM
Is this code has any issues?
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class DoubleTOuch : MonoBehaviour {
public float InitialTouch;
void Update () {
if(Input.GetMouseButtonDown(0))
{
if (Time.time < InitialTouch + 0.5f) {
Debug.Log("DoubleTouch");
}
InitialTouch = Time.time;
}
}
}
InitialTouch will be initialised with its default value of 0. That means that if the user clicks any time in the first 0.5 secs of the game starting, it will be recorded as a "DoubleTouch" (because Time.time < 0 + 0.5f).
Answer by TheFloatingSheep · May 10, 2015 at 08:45 PM
Next time try to google before wasting time by asking. There are a lot of topics about this. You can use this code:
public class DoubleClick : MonoBehaviour {
float doubleClickStart = 0;
void OnMouseUp()
{
if ((Time.time - doubleClickStart) < 0.3f)
{
this.OnDoubleClick();
doubleClickStart = -1;
}
else
{
doubleClickStart = Time.time;
}
}
void OnDoubleClick()
{
Debug.Log("Double Clicked!");
}
}
@The$$anonymous$$iningSheep @jroto23 :) I agree that this answer was quite rude, however it held some truth. Always research first after as a last resort ask... but.... Im just wondering... the time of who was being wasted? If you think that the question was a waste of time, then dont waste your time answering it :) anyway thx for the snippet :)
Answer by Gunging · Jun 10, 2018 at 10:27 PM
I have come up with a very "entangled" code based on arrays and stuff:
static float[] keyEPress = new float[0];
static KeyCode[] keys = new KeyCode[0];
static float keyPressTimeout = 0.5f; //The time (in seconds) to press the same key again to make it count as double click.
public static bool DoubleClick(KeyCode key) {
bool result = false, revisedKey = false;
int availableKeys = 0;
//Removes Forgotten Keys from Array
for (int forg = 0; forg < keys.Length; forg++) {
//If its been a while scince last key press
if (keyEPress[forg] < Time.time) { keys[forg] = KeyCode.None; keys[forg] = 0; } else { availableKeys++; }
}
//Funnels array values into free spaces - Removes "KeyCode.None" elements
KeyCode[] nKeys = new KeyCode[availableKeys]; float[] nKeyEPress = new float[availableKeys];
for (int funn = 0; funn < keys.Length; funn++) {
//If the current key is not "null"
if (keys[funn] != KeyCode.None) {
//Looks at all nKey elements
for (int fum = 0; fum < availableKeys; fum++) {
//If the element is "null"
if (nKeys[fum] == KeyCode.None) {
//This key claims the element
nKeys[fum] = keys[funn];
nKeyEPress[fum] = keyEPress[funn];
}
}
}
}
//Arrays are updated.
keys = nKeys;
keyEPress = nKeyEPress;
//Checks if the key is already assigned to a element in the array
for (int rev = 0; rev < keys.Length; rev++) { if (keys[rev] == key) { revisedKey = true; rev = keys.Length; } }
//If it is a brand new key
if (!revisedKey) {
//Creates a new arrays
KeyCode[] newKeys = new KeyCode[keys.Length + 1];
float[] newKeyEPress = new float[keys.Length + 1];
//Copies the arrays to them
keys.CopyTo(newKeys, 0);
keyEPress.CopyTo(newKeyEPress, 0);
//Assigns current key to the very last element
newKeys[keys.Length] = key;
newKeyEPress[keys.Length] = Time.time + keyPressTimeout; //The current time plus keyPressTimeout - time to double-click
//Updates arrays
keys = newKeys;
keyEPress = newKeyEPress;
//However, if the key is still in the Keys array (It was pressed within 0.5 seconds)
} else {
//The key is now "ignored", thus next press, even if it would be within the original 0.5 seconds, will be counted as original press
for (int ign = 0; ign < keys.Length; ign++) { if (keys[ign] == key) { keyEPress[ign] = 0; ign = keys.Length; } }
result = true; //Returns ture for Double Press
}
return result;
}
This are the freatures of it:
1) Does not need to be called every frame
2) Detects any key (without getting confused)
3) Can be called from anywhere - Its a static method.
The correct way to call it is the following:
void Update() {
//Double Click Mechanic
if (Input.GetKeyDown(KeyCode.P)) {
//If this is the double-click
if (DoubleClick(KeyCode.P)) {
//Double Click Code Here
Debug.Log("Double Clicked!");
} else { //No Double Click
Debug.Log("Clicked!");
}
}
}
I am like 3 years late though lmao.
Answer by Hyper00 · Mar 16, 2020 at 10:30 PM
ну, как-то так)) минут пАру, а с выше и is(ть) над чем WorkЧать**
public float DubleClick_TimeGo = 300; private float DubleClick_Time_ = 0; void Update() { //Double Click if (DubleClick_Time_ > 0) DubleClick_Time_ -= Time.deltaTime * 1000; if (DubleClick_Time_ < 0) DubleClick_Time_ = 0; //corRectIOn opTimeSaTiOn if (Input.GetMouseButtonDown(1)) { //Chandge 0 or 1 if (DubleClick_Time_ > 0) { //DuBleClick Debug.Log("Double Clicked! time="+ DubleClick_Time_); DubleClick_Time_ = 0; //reSet null timer } else if (DubleClick_Time_ == 0) { //firstClick DubleClick_Time_ += DubleClick_TimeGo; //adD(ata) Time Debug.Log("Clicked! time=" + DubleClick_Time_); } } }
Your answer
![](https://koobas.hobune.stream/wayback/20220613194459im_/https://answers.unity.com/themes/thub/images/avi.jpg)