脚本如下:
using UnityEngine;
using UnityEngine.EventSystems;
public delegate void ProcessHandler(float p);
public delegate void FinishTouchHandler(float p);
public class LongTouch : MonoBehaviour,IPointerUpHandler,IPointerExitHandler,IPointerDownHandler
{
public event ProcessHandler m_ProcessDel;
public event FinishTouchHandler m_FinishTouchDel;
public float m_MaxTime = 3f;
private float m_timer = 0;
public bool m_IsStart = false;
private float m_process = 0;
public void AddEvent(ProcessHandler ProDel, FinishTouchHandler FinDel)
{
m_ProcessDel = ProDel;
m_FinishTouchDel = FinDel;
}
public void RemoveEvent()
{
m_ProcessDel = null;
m_FinishTouchDel = null;
}
public void OnPointerDown(PointerEventData eventData)
{
m_IsStart = true;
m_timer = 0;
m_process = 0;
}
public void OnPointerExit(PointerEventData eventData)
{
}
public void OnPointerUp(PointerEventData eventData)
{
if(m_IsStart)m_FinishTouchDel?.Invoke(m_process);
m_IsStart = false;
}
private void Timer()
{
if (m_IsStart)
{
m_timer += Time.deltaTime;
m_process = (m_timer / m_MaxTime) >= 1 ? 1 : (m_timer / m_MaxTime);
m_ProcessDel?.Invoke(m_process);
if (m_timer >= m_MaxTime)
{
m_IsStart = false;
m_FinishTouchDel?.Invoke(1);
m_timer = 0;
}
}
}
void Update () {
Timer();
}
}
使用:注册事件AddEvent,注销事件RemoveEvent
private void Start()
{
ShootBtn.RemoveEvent();
ShootBtn.AddEvent(ShootDownCallBack, ShootFinishCallBack);
}
private void ShootFinishCallBack(float p)
{
}
private void ShootDownCallBack(float p)
{
}