Unity mouse clicks the object and double-clicks the object to trigger different events

Unity mouse clicks the object and double-clicks the object to trigger different events


foreword

The following example adds an image under the Canvas in unity, when the mouse moves to the image and clicks once to trigger the event Debug.Log("SingleClick!"); when the mouse clicks twice on the image to trigger the event Debug.Log("DoubleClick!"); Different response events for double-click and stand-alone


One, the first operation

Add the EventTrigger component on the Canvas or the parent object that needs to be clicked, open the Add New Trigger menu, and add the Pointer Click event and Pointer Down event, as shown in the figure:insert image description here

2. Create a script

1. Create a C# script named ClickHandler and attach it to the game object that needs to be clicked. > The code is as follows (example):

using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;

public class ClickHandler : MonoBehaviour, IPointerClickHandler
{
    
    
    // 上一次点击的时间
    private float lastClickTime = 0;

    // 两次点击之间的最大时间间隔
    private float doubleClickInterval = 0.3f;

    // 单击事件回调函数
    public void OnPointerClick(PointerEventData eventData)
    {
    
    
        if (Time.time - lastClickTime < doubleClickInterval)
        {
    
    
            // 双击事件
            Debug.Log("DoubleClick!");
        }
        else
        {
    
    
            // 单击事件
            Debug.Log("SingleClick!");
        }

        // 更新上一次点击的时间
        lastClickTime = Time.time;
    }
}



insert image description here

Summarize

In the above code, we use lastClickTime to record the time of the last click, and calculate the time interval between two clicks in the callback function. If it is less than doubleClickInterval, it is considered that the double-click event is triggered, otherwise the click event is triggered.

Guess you like

Origin blog.csdn.net/m0_52608003/article/details/129752581