參照UGUI Button源碼做一個類似原聲Button可以以直接拖拽序列化事件的長按 點擊的按鈕腳本,方便開發
using System; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.Events; using UnityEngine.Serialization; public class LongClickBtton : MonoBehaviour, IPointerDownHandler, IPointerUpHandler { /// <summary> /// 長按確認時間 /// </summary> [Range(0.2f, 2f)] public float longTime = 0.8f; [FormerlySerializedAs("onClick"), SerializeField] private UnityEngine.UI.Button.ButtonClickedEvent m_OnClick = new UnityEngine.UI.Button.ButtonClickedEvent(); [FormerlySerializedAs("onLongClick"), SerializeField] private UnityEngine.UI.Button.ButtonClickedEvent m_LongOnClick = new UnityEngine.UI.Button.ButtonClickedEvent(); public UnityEngine.UI.Button.ButtonClickedEvent onClick { get { return m_OnClick; } set{ m_OnClick = value; } } public UnityEngine.UI.Button.ButtonClickedEvent onLongClick { get { return m_LongOnClick; } set{ m_LongOnClick = value; } } private bool ispress = false; private float timer = 0; public void OnPointerDown ( PointerEventData data) { timer = 0f; ispress = true; } public void OnPointerUp ( PointerEventData data) { if (ispress) { if (m_OnClick != null) { m_OnClick.Invoke (); } } ispress = false; timer = 0; } void Update () { if (ispress) { timer += Time.deltaTime; if (timer >= longTime) { if (m_LongOnClick != null) { ispress = false; m_LongOnClick.Invoke (); timer = 0; } } } } }