hellbound/Assets/Scripts/Game/UI/Elements/CheckBox.cs

55 lines
1.2 KiB
C#

using System;
using UnityEngine;
using UnityEngine.UI;
public class CheckBox : MonoBehaviour
{
public event Action<bool> OnChangeState;
public bool IsInteractable => _isInteractable;
public bool IsChecked => _isChecked;
[SerializeField] private Button _button;
[SerializeField] private Image _activeImage;
[SerializeField] private Image _inactiveImage;
private bool _isInteractable = true;
private bool _isChecked = true;
private void Start()
{
_button.onClick.AddListener(OnButtonClick);
}
public void SetState(bool isEnabled)
{
_isChecked = isEnabled;
UpdateView();
}
public void SetInteractable(bool isInteractable)
{
_isInteractable = isInteractable;
UpdateView();
}
private void UpdateView()
{
_activeImage.gameObject.SetActive(_isChecked);
_inactiveImage.gameObject.SetActive(!_isChecked);
_button.interactable = _isInteractable;
_button.targetGraphic = _isChecked ? _activeImage : _inactiveImage;
}
private void OnButtonClick()
{
if (!_isInteractable)
return;
SetState(!_isChecked);
OnChangeState?.Invoke(_isChecked);
}
}