Unity UI案例(长按按钮和双击按钮案例
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
Unity中要实现自己得Button需要编写继承自UnityEngine的Button类,然后再重写按钮按下,抬起,和离开的方法(OnPointerDown,OnPointerUp,OnPointerExit),记录时间差就行了,具体实现看代码:
一:长按按钮实现:
public class LongClickButton : Button {
[Serializable]
public class LongButtonEvent : UnityEvent { }
[SerializeField]
private LongButtonEvent _onLongButtonClick = new LongButtonEvent();
public LongButtonEvent OnLongButtonClick
return _onLongButtonClick;
_onLongButtonClick = value;
private DateTime m_FirstTime;
private DateTime m_SecondTime;
void ResetTime()
m_FirstTime = default(DateTime);
m_SecondTime = default(DateTime);
void Press()
if (OnLongButtonClick != null)
OnLongButtonClick.Invoke();
ResetTime();
public override void OnPointerDown(PointerEventData eventData)
base.OnPointerDown(eventData);
if(m_FirstTime.Equals(default(DateTime)))
m_FirstTime = DateTime.Now;
public override void OnPointerUp(PointerEventData eventData)
base.OnPointerUp(eventData);
if(!m_FirstTime.Equals(default(DateTime)))
m_SecondTime = DateTime.Now;
if(!m_FirstTime.Equals(default(DateTime))&&!m_SecondTime.Equals(default(DateTime)))
var intervalTime = m_SecondTime - m_FirstTime;
float milliTime = intervalTime.Seconds * 1000 + intervalTime.Milliseconds;//毫秒
if (milliTime > 600)
Press();
ResetTime();
public override void OnPointerExit(PointerEventData eventData)
base.OnPointerExit(eventData);
ResetTime();
}
调用: longButton.OnLongButtonClick.AddListener(() => { Debug.Log("LongButtonClick"); });
二.双击按钮实现
public class DoubleClikeButton : Button
[Serializable]
public class DoubleClickEvent : UnityEvent { }
[SerializeField]
private DoubleClickEvent _onDoubleClick = new DoubleClickEvent();
public DoubleClickEvent OnDoubleClick
return _onDoubleClick;
_onDoubleClick = value;
private DateTime m_firstTime;
private DateTime m_SecondTime;
private void ResetTime()
m_firstTime = default(DateTime);
m_SecondTime = default(DateTime);
private void Press()
if (OnDoubleClick != null)
OnDoubleClick.Invoke();
ResetTime();
public override void OnPointerDown(PointerEventData eventData)
base.OnPointerDown(eventData);
if (m_firstTime.Equals(default(DateTime)))
m_firstTime = DateTime.Now;
m_SecondTime = DateTime.Now;
public override void OnPointerUp(PointerEventData eventData)
base.OnPointerUp(eventData);
if (!m_firstTime.Equals(default(DateTime)) && !m_SecondTime.Equals(default(DateTime)))
var intervalTime = m_SecondTime - m_firstTime;
float milliTime = intervalTime.Seconds * 1000 + intervalTime.Milliseconds;
if (milliTime < 400)
Press();
ResetTime();