Skip to content

Instantly share code, notes, and snippets.

@dvdfu
Created June 15, 2022 15:01
Show Gist options
  • Save dvdfu/f10988a97e25b5c6709599593ccccc5e to your computer and use it in GitHub Desktop.
Save dvdfu/f10988a97e25b5c6709599593ccccc5e to your computer and use it in GitHub Desktop.
UI Button for Unity with better responsiveness
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class ButtonUI : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IPointerExitHandler {
public UnityEvent onPressEvent = new UnityEvent();
[SerializeField] Button button;
bool isPressed;
public bool Interactable {
get { return button.interactable; }
set {
button.interactable = value;
Refresh();
}
}
public bool IsPressed() {
return isPressed;
}
public void OnPointerDown(PointerEventData eventData) {
if (Interactable) {
isPressed = true;
Refresh();
}
}
public void OnPointerUp(PointerEventData eventData) {
if (isPressed) {
isPressed = false;
Refresh();
}
}
public void OnPointerExit(PointerEventData eventData) {
if (isPressed) {
isPressed = false;
Refresh();
}
}
public virtual void OnPress() {
onPressEvent.Invoke();
}
protected virtual void Awake() {
button.onClick.AddListener(OnPress);
}
protected virtual void OnEnable() {
Refresh();
}
protected virtual void OnDestroy() {
button.onClick.RemoveListener(OnPress);
}
protected virtual void Refresh() {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment