Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by valdiazdanovic · May 01, 2015 at 04:06 AM · double-click

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;    }
     }
 }
Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

5 Replies

· Add your reply
  • Sort: 
avatar image
5

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;
     }
 }


Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image falantar14 · May 04, 2016 at 06:24 PM 0
Share

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;
   }
avatar image
2

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;
         }
     }
 }
 
Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image tanoshimi · Jul 13, 2017 at 01:07 PM 0
Share

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).

avatar image
-2

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) &lt; 0.3f)
      {
          this.OnDoubleClick();
          doubleClickStart = -1;
      }
      else
      {
          doubleClickStart = Time.time;
      }
  }
  
  void OnDoubleClick()
  {
      Debug.Log("Double Clicked!");
  }
  
 }




Comment
Add comment · Show 3 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Di_o · Jun 01, 2016 at 02:11 PM 0
Share

This is not working... Thx for nothing!

avatar image jroto23 · Jan 24, 2017 at 04:16 PM 1
Share

@ The$$anonymous$$iningSheep...pretty rude

avatar image kornel-l-varga · Sep 28, 2017 at 10:10 AM 1
Share

@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 :)

avatar image
0

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.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

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_);
                 }
             }
         }
    
    
Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

14 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Double-click Detection script on every Game Object? 1 Answer

I cant open any script please help! 2 Answers

GetKeyDown held for too long 1 Answer

Anyone have a double-click script more reliable than mine? 3 Answers

Is it possible to listen for Double clicks on selection grid elements ? 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges