有时候需要用到双击事件,而unity未提供双击控件,在此提供两种双击事件方法,进攻参考:
1)此方法为通过unityevent来实现
首先新建image(或其他不带点击事件的控件),添加如下脚本,然后就可以像button控件单击事件一样添加双击方法,设定双击间隔为0.5s
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
public class DBlick1 : MonoBehaviour,IPointerDownHandler{
[SerializeField]
UnityEvent doubleClick = new UnityEvent(); public float Interval = 0.5f;
private float firstClicked = 0;
private float secondClicked = 0;
public void OnPointerDown(PointerEventData eventData)
secondClicked = Time.realtimeSinceStartup;
if(secondClicked-firstClicked<Interval)
doubleClick.Invoke();
firstClicked = secondClicked;
// Use this for initialization
void Start () {
// Update is called once per frame
void Update () {
2)通过button在button绑定的方法中触发
public float Interval = 0.5f;
private float firstClicked = 0;
private float secondClicked = 0;
public void OnDoubleClicked()
secondClicked = Time.realtimeSinceStartup;
if (secondClicked - firstClicked < Interval)
print("clicked");
firstClicked = secondClicked;
3)触屏简单方法
(最近刚发现的触屏双击方法,更新与2018-4-18)
采用input类方法即
if (Input.GetTouch(0).tapCount == 2)
GetTouch(0)表示第一次点击屏幕,tapCount表示点击次数,上述即为如果点击屏幕等于两次即。。。。。
1)第一种方法适合存在众多双击事件时使用,第二种则适合只有一个单击事件时使用,两者并无太大差别,均可使用,适合与否只是从代码量上考虑
2)两种方法均存在一个问题,即当鼠标连续点击三次时,由于逻辑的问题,事件会触发两次,可以增加一个变量来进行控制,在此只是提供两种双击事件的思路
上述问题2)解决(同时通过更改clickedCount可实现三点击,四点击等)
public int clickedCount = 2;
public float clickedInterval = 0.5f;
private float lastClickedTime = 0;
private float count = 0;
public void OnClicked()
float interval = Time.realtimeSinceStartup - lastClickedTime;
if(interval <= clickedInterval)
count++;
if(count==clickedCount-1)
//TODO:
count = 0;
lastClickedTime = Time.realtimeSinceStartup;