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

66 lines
1.7 KiB
C#

using System;
using UnityEngine;
using UnityEngine.UI;
namespace Ashwild.Settings
{
/// <summary>
/// A reusable toggle. Pure UI: it knows nothing about which bool setting it drives. The panel
/// calls <see cref="Init"/> once to register the action to run when the user flips it, then
/// reflects state through <see cref="SetValue"/>.
/// </summary>
[DisallowMultipleComponent]
public class SettingToggleWidget : MonoBehaviour
{
#region Serialized Fields
[Header("References")]
[SerializeField] private Toggle toggle;
#endregion
#region State
private Action<bool> onChanged;
#endregion
#region Public API
/// <summary>
/// Registers the action to run when the user flips the toggle. Call once.
/// </summary>
public void Init(Action<bool> onChanged)
{
if (toggle == null)
{
Debug.LogError($"[SettingToggleWidget] '{name}' has no Toggle assigned.", this);
return;
}
this.onChanged = onChanged;
toggle.onValueChanged.RemoveListener(HandleToggleChanged);
toggle.onValueChanged.AddListener(HandleToggleChanged);
}
/// <summary>
/// Displays the given state without invoking the apply action.
/// </summary>
public void SetValue(bool value)
{
if (toggle != null) toggle.SetIsOnWithoutNotify(value);
}
#endregion
#region Event Handlers
/// <summary>
/// Runs the apply action with the user-driven state.
/// </summary>
private void HandleToggleChanged(bool value) => onChanged?.Invoke(value);
#endregion
}
}