2026-03-22 스왑버튼 그룹구현
This commit is contained in:
108
Assets/02_Scripts/UI/_Shared/Buttons/SwapButton.cs
Normal file
108
Assets/02_Scripts/UI/_Shared/Buttons/SwapButton.cs
Normal file
@@ -0,0 +1,108 @@
|
||||
using UnityEngine;
|
||||
using UnityEngine.Events;
|
||||
using UnityEngine.EventSystems;
|
||||
using UnityEngine.UI;
|
||||
|
||||
[ExecuteAlways]
|
||||
[RequireComponent(typeof(Image))]
|
||||
public class SwapButton : MonoBehaviour, IPointerClickHandler
|
||||
{
|
||||
[SerializeField] private SwapButtonGroup _group;
|
||||
public SwapButtonGroup Group
|
||||
{
|
||||
get => _group;
|
||||
set
|
||||
{
|
||||
if (_group != null) _group.UnregisterButton(this);
|
||||
_group = value;
|
||||
if (_group != null) _group.RegisterButton(this);
|
||||
}
|
||||
}
|
||||
|
||||
[Space(10)]
|
||||
|
||||
public Image TargetImage;
|
||||
|
||||
[Space(10)]
|
||||
|
||||
public Sprite TrueSprite;
|
||||
public UnityEvent TrueEvent = new UnityEvent();
|
||||
|
||||
public Sprite FalseSprite;
|
||||
public UnityEvent FalseEvent = new UnityEvent();
|
||||
|
||||
[SerializeField] private bool _trueA_FalseB = true;
|
||||
|
||||
public bool TrueA_FalseB
|
||||
{
|
||||
get => _trueA_FalseB;
|
||||
set
|
||||
{
|
||||
if (_trueA_FalseB == value) return;
|
||||
|
||||
_trueA_FalseB = value;
|
||||
UpdateVisual(); // 값이 바뀔 때마다 자동으로 실행!
|
||||
|
||||
if (_trueA_FalseB && _group != null)
|
||||
{
|
||||
_group.OnButtonSelected(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
TargetImage = GetComponent<Image>();
|
||||
|
||||
// 시작할 때 그룹이 설정되어 있다면 등록
|
||||
if (_group != null) _group.RegisterButton(this);
|
||||
|
||||
}
|
||||
private void Start()
|
||||
{
|
||||
UpdateVisual();
|
||||
}
|
||||
|
||||
public void OnPointerClick(PointerEventData eventData)
|
||||
{
|
||||
if (_group != null)
|
||||
{
|
||||
// 라디오 버튼 모드: 이미 선택된 건 다시 눌러도 무반응
|
||||
if (_trueA_FalseB) return;
|
||||
|
||||
TrueA_FalseB = true; // 나를 True 상태로
|
||||
TrueEvent?.Invoke();
|
||||
}
|
||||
else
|
||||
{
|
||||
// 그룹이 없으면 기존처럼 토글
|
||||
TrueA_FalseB = !TrueA_FalseB;
|
||||
|
||||
if (TrueA_FalseB)
|
||||
TrueEvent?.Invoke();
|
||||
else
|
||||
FalseEvent?.Invoke();
|
||||
}
|
||||
}
|
||||
|
||||
private void OnValidate()
|
||||
{
|
||||
UpdateVisual();
|
||||
|
||||
if (_trueA_FalseB && _group != null)
|
||||
{
|
||||
_group.OnButtonSelected(this);
|
||||
}
|
||||
}
|
||||
public void UpdateVisual()
|
||||
{
|
||||
if (TargetImage == null) return;
|
||||
TargetImage.sprite = _trueA_FalseB ? TrueSprite : FalseSprite;
|
||||
}
|
||||
|
||||
private void OnDestroy()
|
||||
{
|
||||
// 오브젝트 삭제 시 그룹에서 해제
|
||||
if (_group != null) _group.UnregisterButton(this);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user