RepeatButton 누르고 있는 동안 이벤트가 반복 발생하는 버튼
using System;
using System.Collections;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEngine.Serialization;
using UnityEngine.UI;
namespace UI
{
public class RepeatButton : Selectable, IPointerDownHandler, IPointerUpHandler, IPointerExitHandler
{
[SerializeField] private float interval = 0.1f;
[SerializeField] private float delay = 1.0f;
[SerializeField] private ButtonRepeatEvent onRepeat = new ButtonRepeatEvent();
private bool isPointDown = false;
private float lastInvokeTime;
private float delayTime = 0f;
public ButtonRepeatEvent OnRepeat => onRepeat;
// Use this for initialization
protected override void Start()
{
base.Start();
delayTime = delay;
}
protected override void OnDisable()
{
base.OnDisable();
isPointDown = false;
delayTime = delay;
}
void Update()
{
if (!IsInteractable() && isPointDown)
{
isPointDown = false;
delayTime = delay;
return;
}
if (isPointDown)
{
if ((delayTime -= Time.deltaTime) > 0f)
{
return;
}
if (Time.time - lastInvokeTime > interval)
{
Repeat();
lastInvokeTime = Time.time;
}
}
}
private void Repeat()
{
if (!IsActive() || !IsInteractable())
return;
onRepeat.Invoke();
}
public virtual void OnPointerClick(PointerEventData eventData)
{
if (eventData.button != PointerEventData.InputButton.Left)
return;
Repeat();
}
public override void OnPointerDown(PointerEventData eventData)
{
base.OnPointerExit(eventData);
isPointDown = true;
delayTime = delay;
if (IsInteractable())
{
DoStateTransition(SelectionState.Pressed, false);
}
}
public override void OnPointerUp(PointerEventData eventData)
{
base.OnPointerExit(eventData);
isPointDown = false;
delayTime = delay;
DoStateTransition(currentSelectionState, false);
}
public override void OnPointerExit(PointerEventData eventData)
{
base.OnPointerExit(eventData);
isPointDown = false;
delayTime = delay;
DoStateTransition(currentSelectionState, false);
}
[Serializable]
public class ButtonRepeatEvent : UnityEvent { }
}
}
'유니티 & C#' 카테고리의 다른 글
Pagination of IEnumerable<T> (0) | 2020.09.29 |
---|---|
BundleTool - 유니티에서 빌드된 aab 파일을 안드로이드에 설치 (0) | 2020.09.20 |
유니티에서 컴파일러 Warning 로그 제거하기 (0) | 2020.07.13 |
엑셀의 모든 시트를 각각의 csv로 내보내기 (0) | 2020.07.12 |
유니티 프로젝트 창 아이콘 Custom GUI (0) | 2020.06.30 |