using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; using DG.Tweening; public class UIButtonInteraction : MonoBehaviour, IPointerEnterHandler, IPointerClickHandler { private UIButtonType type = UIButtonType.Default; private Selectable selectable; [Header("Animation")] [SerializeField] private float clickScale = 0.95f; [SerializeField] private float duration = 0.1f; [SerializeField] private Ease ease = Ease.OutQuad; private Vector3 originalScale; private Tween scaleTween; void Awake() { originalScale = transform.localScale; selectable = GetComponent(); UIButtonSoundTag tag = GetComponent(); if (tag != null) type = tag.type; // Special handling for different types of Selectables if (selectable is Button button) { button.onClick.AddListener(OnButtonClicked); } else if (selectable is Toggle toggle) { toggle.onValueChanged.AddListener(OnToggleChanged); } else if (selectable is Slider slider) { slider.onValueChanged.AddListener(OnSliderChanged); } else if (selectable is Dropdown dropdown) { dropdown.onValueChanged.AddListener(OnDropdownChanged); } else if (selectable is TMPro.TMP_Dropdown tmpDropdown) { tmpDropdown.onValueChanged.AddListener(OnDropdownChanged); } } private void OnButtonClicked() { if (selectable != null && !selectable.interactable) return; UISoundRouter.Instance?.PlayClick(type); PlayClickAnimation(); } private void OnToggleChanged(bool isOn) { if (selectable != null && !selectable.interactable) return; UISoundRouter.Instance?.PlayClick(type); } private void OnDropdownChanged(int value) { if (selectable != null && !selectable.interactable) return; UISoundRouter.Instance?.PlayClick(type); } private void OnSliderChanged(float value) { // Sliders usually don't play sound on every value change } public void OnPointerEnter(PointerEventData eventData) { if (selectable != null && !selectable.interactable) return; UISoundRouter.Instance?.PlayHover(type); } public void OnPointerClick(PointerEventData eventData) { // If it's a Button, Toggle or Dropdown, we already play sound in their specific events if (selectable is Button || selectable is Toggle || selectable is Dropdown || selectable is TMPro.TMP_Dropdown) return; if (selectable != null && !selectable.interactable) return; UISoundRouter.Instance?.PlayClick(type); PlayClickAnimation(); } void PlayClickAnimation() { scaleTween?.Kill(); transform.localScale = originalScale; scaleTween = transform .DOScale(originalScale * clickScale, duration) .SetEase(ease) .SetUpdate(true) .OnComplete(() => { transform .DOScale(originalScale, duration) .SetEase(ease) .SetUpdate(true); }); } }