Files
2026-06-26 16:23:20 +02:00

96 lines
2.9 KiB
C#
Raw Permalink 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 TMPro;
using UnityEngine;
using UnityEngine.UI;
namespace Ashwild.Settings
{
/// <summary>
/// A reusable slider + value label. It is pure UI: it knows nothing about which setting it
/// drives. The hosting panel calls <see cref="Init"/> 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 <see cref="SetValue"/>. The range is applied to the slider in <see cref="Init"/>, so
/// a control can never be stuck at the slider's default 01 range.
/// </summary>
[DisallowMultipleComponent]
public class SettingSliderWidget : MonoBehaviour
{
#region Serialized Fields
[Header("References")]
[SerializeField] private Slider slider;
[SerializeField] private TMP_Text valueLabel;
#endregion
#region State
private Action<float> onChanged;
private float labelScale = 1f;
private string labelFormat = "{0:F0}";
#endregion
#region Public API
/// <summary>
/// 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 <see cref="SetValue"/>).
/// </summary>
public void Init(float min, float max, float labelScale, string labelFormat, Action<float> 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);
}
/// <summary>
/// Displays the given value without invoking the apply action.
/// </summary>
public void SetValue(float value)
{
if (slider == null) return;
slider.SetValueWithoutNotify(value);
UpdateLabel(value);
}
#endregion
#region Event Handlers
/// <summary>
/// Updates the label and runs the apply action with the user-driven value.
/// </summary>
private void HandleSliderChanged(float value)
{
UpdateLabel(value);
onChanged?.Invoke(value);
}
#endregion
#region Internal Helpers
/// <summary>
/// Formats and shows the scaled value, when a label is wired.
/// </summary>
private void UpdateLabel(float value)
{
if (valueLabel != null) valueLabel.text = string.Format(labelFormat, value * labelScale);
}
#endregion
}
}