SoFunction
Updated on 2025-03-07

Unity realizes detection of double-click and long-press on mouse

In unity, we will encounter many mouse events. Although relevant click and drag methods are given in unity, these methods are only applicable to UI and colliders. So, how to directly use code to detect double-click and long-press of the mouse?
First we need several variables to save time to determine whether to press or click.

private float main_time;
public float click_time;
private float two_click_time;
private int count;

Let’s talk about the uses of these variables first. main_time is mainly used to detect whether the mouse is clicked once or the mouse is pressed for a long time. click_time mainly detects the interval between the first click and the second click, and has determined whether it is a double-click. The last variable two_click_time is mainly used to detect. If you click once first and then click twice in a row, is it the next two times a double-click? count is mainly used to count the number of mouse clicks.
In order to detect the action of each frame of the mouse, we need to put the following code in Update.

if ((0)){
 if (main_time == 0.0f){
  main_time = ;
 }
 if ( - main_time > 0.2f) {
  //Put it here for long pressing and pressing }
}
if ((0))
  {
   if ( - main_time < 0.2f)
   {//When the mouse is raised, the time it is pressed to lift is detected. If it is less than 2.0f, it is determined to be a click.   
    if (two_twoClicks != 0 &&  - two_twoClicks < 0.2f)
    {
     count = 2;
    }
    else
    {
     count++;
     if (count == 1)
     {
      time = ;
     }
    }
    if (count == 2
     && ((time != 0 &&  - time < 0.2f) || (two_twoClicks != 0 &&  - two_twoClicks < 0.2f)))
    {//If the two clicks event is less than 0.2f, it is judged as double hit    //The code block executed when double-clicking     count = 0;
    }    
    if (count == 2 && ( - time > 0.2f || -two_twoClicks > 0.2f))
    {
     two_twoClicks = ;
     count = 0;
    }
    main_time = 0.0f;
   }
   else
   {
    main_time = 0.0f;
   }
  }

In this code, I used the and. The reason why I didn't use it is because when we click the mouse once, the and will be called at the same time, so it is impossible to tell whether to hold it long or click. So we can only detect the time of pressing and judge the mouse behavior based on the time of pressing. However, this large piece of code is very cumbersome and difficult to understand, but the runtime effect is still very good.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.