com.alicizax.unity.ui.exten.../Runtime/UXComponent/Button/UXButton.cs
2026-03-18 16:01:18 +08:00

126 lines
3.1 KiB
C#

using System;
using System.Collections;
using System.Collections.Generic;
using AlicizaX.UI;
using AlicizaX.UI.Extension;
using UnityEngine.EventSystems;
#if INPUTSYSTEM_SUPPORT
using UnityEngine.InputSystem;
#endif
namespace UnityEngine.UI
{
[AddComponentMenu("UI/UXButton", 30)]
public class UXButton : UXSelectable, IPointerClickHandler, ISubmitHandler, IButton
#if INPUTSYSTEM_SUPPORT
, IHotkeyTrigger
#endif
{
#if INPUTSYSTEM_SUPPORT
InputActionReference IHotkeyTrigger.HotkeyAction
{
get => _hotkeyAction;
set => _hotkeyAction = value;
}
EHotkeyPressType IHotkeyTrigger.HotkeyPressType
{
get => _hotkeyPressType;
set => _hotkeyPressType = value;
}
void IHotkeyTrigger.HotkeyActionTrigger()
{
if (interactable)
{
OnSubmit(null);
}
}
[SerializeField] internal InputActionReference _hotkeyAction;
[SerializeField] internal EHotkeyPressType _hotkeyPressType;
public InputActionReference HotKeyRefrence
{
get { return _hotkeyAction; }
}
#endif
[SerializeField] private AudioClip hoverAudioClip;
[SerializeField] private AudioClip clickAudioClip;
protected UXButton()
{
}
public override void OnPointerEnter(PointerEventData eventData)
{
base.OnPointerEnter(eventData);
PlayAudio(hoverAudioClip);
}
public virtual void OnPointerClick(PointerEventData eventData)
{
if (eventData.button != PointerEventData.InputButton.Left)
return;
Press();
PlayAudio(clickAudioClip);
}
public virtual void OnSubmit(BaseEventData eventData)
{
Press();
PlayAudio(clickAudioClip);
if (!IsActive() || !IsInteractable())
return;
DoStateTransition(SelectionState.Pressed, false);
StartCoroutine(OnFinishSubmit());
}
private IEnumerator OnFinishSubmit()
{
var fadeTime = colors.fadeDuration;
var elapsedTime = 0f;
while (elapsedTime < fadeTime)
{
elapsedTime += Time.unscaledDeltaTime;
yield return null;
}
DoStateTransition(currentSelectionState, false);
}
private void PlayAudio(AudioClip clip)
{
if (clip && UXComponentExtensionsHelper.AudioHelper != null)
UXComponentExtensionsHelper.AudioHelper.PlayAudio(clip);
}
[SerializeField] private Button.ButtonClickedEvent m_OnClick = new Button.ButtonClickedEvent();
public Button.ButtonClickedEvent onClick
{
get { return m_OnClick; }
set { m_OnClick = value; }
}
private void Press()
{
if (!IsActive() || !IsInteractable())
return;
UISystemProfilerApi.AddMarker("Button.onClick", this);
m_OnClick.Invoke();
}
}
}