RandomGFGoStop/Assets/Scripts/UGUISlideBar.cs

94 lines
2.6 KiB
C#

using UnityEngine;
using UnityEngine.EventSystems;
public class UGUISlideBar : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
[SerializeField] private RectTransform FillRT;
[SerializeField] private TMPro.TextMeshProUGUI PercentTMP;
[SerializeField] private bool InitOnPointerUp = false;
private RectTransform rt;
private float MaxWidth;
private Camera uiCamera;
private bool checkable = false;
public System.Action OnValueChanged;
public bool Controlable { get; set; } = true;
/// <summary>Normalized Value. 0 ~ 1 </summary>
public float Value
{
get
{
float result = Mathf.Clamp(FillRT.sizeDelta.x / MaxWidth, 0f, 1f);
return result;
}
set
{
FillRT.sizeDelta = new Vector2(Mathf.Clamp(value * MaxWidth, 0, MaxWidth), FillRT.sizeDelta.y);
if (PercentTMP != null)
PercentTMP.text = (FillRT.sizeDelta.x / MaxWidth * 100f).ToString("N1") + "%";
OnValueChanged?.Invoke();
}
}
private void Awake()
{
rt = this.GetComponent<RectTransform>();
MaxWidth = rt.rect.width;
uiCamera = this.transform.root.Find("PopupCanvas").GetComponent<Canvas>().worldCamera;
}
private void OnEnable()
{
Value = 0;
}
private void OnDisable()
{
checkable = false;
}
private void Update()
{
if (!checkable || !Controlable) return;
#if UNITY_EDITOR
if (uiCamera != null && Input.GetMouseButton(0))
#elif UNITY_ANDROID
if (uiCamera != null && Input.touchCount > 0)
#endif
{
Vector2 local;
#if UNITY_EDITOR
if (RectTransformUtility.ScreenPointToLocalPointInRectangle(FillRT, Input.mousePosition, uiCamera, out local))
#elif UNITY_ANDROID
if (RectTransformUtility.ScreenPointToLocalPointInRectangle(FillRT, Input.GetTouch(0).position, uiCamera, out local))
#endif
{
FillRT.sizeDelta = new Vector2(Mathf.Clamp(local.x, 0, MaxWidth), FillRT.sizeDelta.y);
OnValueChanged?.Invoke();
if (PercentTMP != null)
PercentTMP.text = (FillRT.sizeDelta.x / MaxWidth * 100f).ToString("N1") + "%";
}
}
}
public void OnPointerDown(PointerEventData eventData)
{
if (Controlable)
checkable = true;
}
public void OnPointerUp(PointerEventData eventData)
{
if (Controlable)
checkable = false;
if (InitOnPointerUp)
Value = 0f;
}
}