You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

61 lines
1.5 KiB

using System;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEngine.UI;
[RequireComponent(typeof(Button))]
public class ExtendButton : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
[SerializeField] Button button;
[SerializeField] float pressedInternalTime = 0.5f;
[SerializeField] float pressedTickIntervalTime = 0.1f;
bool isPressed;
float pressedTime;
float prevCallPressedEventTime;
public Button ButtonComponent => button;
public event Action OnPressedShortly;
public event Action OnLongPressed;
public event Action OnLongPressedReleased;
private void LateUpdate()
{
if (!isPressed) return;
if (Time.time >= prevCallPressedEventTime)
{
OnLongPressed?.Invoke();
prevCallPressedEventTime += pressedTickIntervalTime;
}
}
public void OnPointerDown(PointerEventData eventData)
{
if(!button.interactable) return;
isPressed = true;
pressedTime = Time.time;
prevCallPressedEventTime = pressedTime + pressedInternalTime;
}
public void OnPointerUp(PointerEventData eventData)
{
if (pressedTime + pressedInternalTime <= Time.time)
OnLongPressedReleased?.Invoke();
else
OnPressedShortly?.Invoke();
prevCallPressedEventTime = 0;
pressedTime = 0;
isPressed = false;
}
private void OnValidate()
{
if (button == null)
button = GetComponent<Button>();
}
}