Skip to content

Commit e848948

Browse files
committed
script that enables repeated events when long-pressing a button
1 parent 298e56d commit e848948

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

unity/UnityUIUtil.cs

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -625,6 +625,61 @@ void setIdFromIndex(int dropdown_index)
625625

626626

627627

628+
629+
630+
/// <summary>
631+
/// Attach this script to a unity UI widget and then you will get onLongPress() event
632+
/// after pressing down for HoldTime. If RepeatTime > 0, then onLongPress will continue
633+
/// to fire at that time interval until button is released.
634+
/// Notes: https://forum.unity.com/threads/long-press-gesture-on-ugui-button.264388/
635+
/// </summary>
636+
public class ButtonLongPress : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IPointerExitHandler
637+
{
638+
public float HoldTime = 1.0f;
639+
public float RepeatTime = 0.0f;
640+
641+
// todo: use this to avoid Button.OnClick() from also firing during a longpress?
642+
//private bool held = false;
643+
//public UnityEvent onClick = new UnityEvent();
644+
645+
public UnityEvent onLongPress = new UnityEvent();
646+
647+
public void OnPointerDown(PointerEventData eventData)
648+
{
649+
//held = false;
650+
Invoke("OnLongPress", HoldTime);
651+
}
652+
653+
public void OnPointerUp(PointerEventData eventData)
654+
{
655+
CancelInvoke("OnLongPress");
656+
657+
//if (!held)
658+
// onClick.Invoke();
659+
}
660+
661+
public void OnPointerExit(PointerEventData eventData)
662+
{
663+
CancelInvoke("OnLongPress");
664+
}
665+
666+
void OnLongPress()
667+
{
668+
//held = true;
669+
onLongPress.Invoke();
670+
671+
// spawn repeat
672+
if (RepeatTime > 0) {
673+
Invoke("OnLongPress", RepeatTime);
674+
}
675+
}
676+
}
677+
678+
679+
680+
681+
682+
628683
// create text mesh
629684
// [TODO] only used by HUDRadialMenu, can get rid of when
630685
// we replace that with fText...

0 commit comments

Comments
 (0)