lingyifang4

[UnityUI]UGUI按钮长按效果

  1. using UnityEngine;  
  2. using System.Collections;  
  3. using UnityEngine.EventSystems;  
  4. using UnityEngine.Events;  
  5.   
  6. public class RepeatButton : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IPointerExitHandler {  
  7.   
  8.     public bool invokeOnce = false;//是否只调用一次  
  9.     private bool hadInvoke = false;//是否已经调用过  
  10.   
  11.     public float interval = 0.1f;//按下后超过这个时间则认定为"长按"  
  12.     private bool isPointerDown = false;  
  13.     private float recordTime;  
  14.   
  15.     public UnityEvent onPress = new UnityEvent();//按住时调用  
  16.     public UnityEvent onRelease = new UnityEvent();//松开时调用  
  17.   
  18.     void Start ()   
  19.     {  
  20.       
  21.     }  
  22.       
  23.     void Update ()   
  24.     {  
  25.         if (invokeOnce && hadInvoke) return;  
  26.         if (isPointerDown)  
  27.         {  
  28.             if ((Time.time - recordTime) > interval)  
  29.             {  
  30.                 onPress.Invoke();  
  31.                 hadInvoke = true;  
  32.             }  
  33.         }  
  34.     }  
  35.   
  36.     public void OnPointerDown(PointerEventData eventData)  
  37.     {  
  38.         isPointerDown = true;  
  39.         recordTime = Time.time;  
  40.     }  
  41.   
  42.     public void OnPointerUp(PointerEventData eventData)  
  43.     {  
  44.         isPointerDown = false;  
  45.         hadInvoke = false;  
  46.         onRelease.Invoke();  
  47.     }  
  48.   
  49.     public void OnPointerExit(PointerEventData eventData)  
  50.     {  
  51.         isPointerDown = false;  
  52.         hadInvoke = false;  
  53.         onRelease.Invoke();  
  54.     }  
  55. }  

评论