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

发布时间:2023年12月24日

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

脚本如下:

using UnityEngine;
using UnityEngine.EventSystems;

public delegate void ProcessHandler(float p);

public delegate void FinishTouchHandler(float p);

/// <summary>
/// 长触摸事件
/// </summary>
public class LongTouch : MonoBehaviour,IPointerUpHandler,IPointerExitHandler,IPointerDownHandler
{
    /// <summary>
    /// 进度委托
    /// </summary>
    public event ProcessHandler m_ProcessDel;

    /// <summary>
    /// 完成委托
    /// </summary>
    public event FinishTouchHandler m_FinishTouchDel;

    /// <summary>
    /// 最长时间3秒
    /// </summary>
    public float m_MaxTime = 3f;

    /// <summary>
    /// 计时器使用
    /// </summary>
    private float m_timer = 0;

    /// <summary>
    /// 计时器开关
    /// </summary>
    public bool m_IsStart = false;

    /// <summary>
    /// 进度条
    /// </summary>
    private float m_process = 0;

    /// <summary>
    /// 添加事件
    /// </summary>
    public void AddEvent(ProcessHandler ProDel, FinishTouchHandler FinDel)
    {
        m_ProcessDel = ProDel;
        m_FinishTouchDel = FinDel;
    }

    /// <summary>
    /// 移除事件
    /// </summary>
    public void RemoveEvent()
    {
        m_ProcessDel = null;
        m_FinishTouchDel = null;
    }

    /// <summary>
    /// 按下事件
    /// </summary>
    /// <param name="eventData"></param>
    public void OnPointerDown(PointerEventData eventData)
    {
        m_IsStart = true;
        m_timer = 0;
        m_process = 0;
    }

    /// <summary>
    /// 离开事件
    /// </summary>
    /// <param name="eventData"></param>
    public void OnPointerExit(PointerEventData eventData)
    {
        //m_IsStart = false;
    }

    /// <summary>
    /// 抬起事件
    /// </summary>
    /// <param name="eventData"></param>
    public void OnPointerUp(PointerEventData eventData)
    {
        if(m_IsStart)m_FinishTouchDel?.Invoke(m_process);
        m_IsStart = false;
    }

    /// <summary>
    /// 计时器
    /// </summary>
    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)
    {

    }



文章来源:https://blog.csdn.net/qq_42194657/article/details/135186531
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。