using System; using TMPro; using UnityEngine; using UnityEngine.UI; namespace Ashwild.Settings { /// /// A reusable slider + value label. It is pure UI: it knows nothing about which setting it /// drives. The hosting panel calls once to hand it its range, label format /// and the action to run when the user moves it; afterwards the panel pushes the current value /// through . The range is applied to the slider in , so /// a control can never be stuck at the slider's default 0–1 range. /// [DisallowMultipleComponent] public class SettingSliderWidget : MonoBehaviour { #region Serialized Fields [Header("References")] [SerializeField] private Slider slider; [SerializeField] private TMP_Text valueLabel; #endregion #region State private Action onChanged; private float labelScale = 1f; private string labelFormat = "{0:F0}"; #endregion #region Public API /// /// Configures the slider with its range and label format, and registers the action to run /// when the user drags it. Call once (the apply action is not invoked by ). /// public void Init(float min, float max, float labelScale, string labelFormat, Action onChanged) { if (slider == null) { Debug.LogError($"[SettingSliderWidget] '{name}' has no Slider assigned.", this); return; } this.labelScale = labelScale; this.labelFormat = labelFormat; this.onChanged = onChanged; slider.minValue = min; slider.maxValue = max; slider.onValueChanged.RemoveListener(HandleSliderChanged); slider.onValueChanged.AddListener(HandleSliderChanged); } /// /// Displays the given value without invoking the apply action. /// public void SetValue(float value) { if (slider == null) return; slider.SetValueWithoutNotify(value); UpdateLabel(value); } #endregion #region Event Handlers /// /// Updates the label and runs the apply action with the user-driven value. /// private void HandleSliderChanged(float value) { UpdateLabel(value); onChanged?.Invoke(value); } #endregion #region Internal Helpers /// /// Formats and shows the scaled value, when a label is wired. /// private void UpdateLabel(float value) { if (valueLabel != null) valueLabel.text = string.Format(labelFormat, value * labelScale); } #endregion } }