UGUI长按按钮的实现(技能蓄力使用)

UGUI长按按钮的实现(技能蓄力使用)

  • 脚本如下:
  • 使用:注册事件AddEvent,注销事件RemoveEvent

脚本如下:

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;

    /// 
    /// 最长时间3秒
    /// 
    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)
    {
        //m_IsStart = false;
    }

    /// 
    /// 抬起事件
    /// 
    /// 
    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;
            }
        }
    }

	// Update is called once per frame
	void Update () {
        Timer();
    }
}

使用:注册事件AddEvent,注销事件RemoveEvent

private void Start()
{	
	ShootBtn.RemoveEvent();
	ShootBtn.AddEvent(ShootDownCallBack, ShootFinishCallBack);
}


    private void ShootFinishCallBack(float p)
    {
        

    }


    private void ShootDownCallBack(float p)
    {

    }



你可能感兴趣的:(Unity,Unity,UGUI,长按事件)