Unity中要实现单击交互很简单,使用Button、Toggle、EventTrigger事件都可以实现,但是要实现双击某个物体触发交互事件,则需要另外编写脚本。
方法是在EventTrigger中IPointerClickHandler下的点击事件中编写通过短时间间隔内捕获到两次点击事件的算法模拟为双击事件,具体实现如下:
using UnityEngine;
using UnityEngine.EventSystems;
public class ContinuousClickHandler : MonoBehaviour, IPointerClickHandler
{
public float clickInterval = 0.3f; // 连续点击间隔阈值
private float lastClickTime;
public void OnPointerClick(PointerEventData eventData)
{
float timeSinceLastClick = Time.time - lastClickTime;
if (timeSinceLastClick <= clickInterval)
{
// 连续点击事件
Debug.Log("双击了!");
}
lastClickTime = Time.time;
}
}