Files
zeling_v2/Assets/_Game/Scripts/UI/Controls/UISlider.cs
2026-06-07 11:49:55 +08:00

53 lines
1.9 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
using TMPro;
namespace BaseGames.UI
{
/// <summary>
/// 滑条控件封装Slider + 实时数值标签 + 一行式 <see cref="Bind"/>
/// 消除设置面板里"移除监听→设值→加监听→更新标签"的重复样板。
/// </summary>
[DisallowMultipleComponent]
public class UISlider : MonoBehaviour
{
[SerializeField] private Slider _slider;
[Tooltip("实时数值标签(可空)。")]
[SerializeField] private TMP_Text _valueLabel;
[Tooltip("数值标签格式(当未传 fmt 委托时使用)。例:\"{0:0}\"、\"{0:0}%\"。")]
[SerializeField] private string _format = "{0:0}";
private Func<float, string> _fmt;
public Slider Slider => _slider;
public float Value => _slider != null ? _slider.value : 0f;
/// <summary>
/// 绑定取值范围、初值与变更回调。<paramref name="fmt"/> 可自定义数值标签文本(优先于 <see cref="_format"/>)。
/// </summary>
public void Bind(float min, float max, float value, UnityAction<float> onChanged, Func<float, string> fmt = null)
{
if (_slider == null) return;
_slider.onValueChanged.RemoveAllListeners();
_slider.minValue = min;
_slider.maxValue = max;
_slider.value = Mathf.Clamp(value, min, max);
_fmt = fmt;
UpdateLabel(_slider.value);
_slider.onValueChanged.AddListener(v =>
{
onChanged?.Invoke(v);
UpdateLabel(v);
});
}
private void UpdateLabel(float v)
{
if (_valueLabel == null) return;
_valueLabel.text = _fmt != null ? _fmt(v) : string.Format(_format, v);
}
}
}