using System.Collections.Generic; using TMPro; using UnityEngine; // 스크린 스페이스 선택지 UI 싱글턴. // DialogPlayer가 Show()를 await해서 선택된 인덱스를 받아감. public class ChoiceHud : MonoBehaviour { public static ChoiceHud Instance { get; private set; } [Header("Refs")] [SerializeField] private GameObject _root; [SerializeField] private Transform _rowContainer; [SerializeField] private DialogChoiceRow _rowPrefab; [SerializeField] private GameObject _dialogSelectPanelObj; [SerializeField] private TMP_Text ChoiceQuestion; [SerializeField] private RectTransform _ScrollRect; [Header("Layout")] [Tooltip("선택지 한 줄의 높이")] [SerializeField] private float _rowHeight = 40f; [Tooltip("이 줄 수까지만 높이를 늘리고, 넘어가면 스크롤로 본다")] [SerializeField] private int _maxVisibleRows = 3; private readonly List _rows = new(); private AwaitableCompletionSource _completion; private void Awake() { if (Instance != null && Instance != this) { Destroy(gameObject); return; } Instance = this; if (_root == null) _root = gameObject; Hide(); } private void OnDestroy() { if (Instance == this) Instance = null; } private void OnDisable() { // 진행 중 대기 정리 (씬 전환 등으로 비활성화될 때) _completion?.TrySetCanceled(); _completion = null; } // 대기 중인 선택을 취소하고 메뉴를 닫는다 (다른 NPC와 대화를 새로 시작할 때 등). // 취소된 쪽의 await Show(...)는 OperationCanceledException으로 빠져나간다. public void CancelPending() { _completion?.TrySetCanceled(); } public async Awaitable Show(string choiceQuestion, List choices) { if (choices == null || choices.Count == 0) return 0; // 이전 호출이 아직 대기 중이면 먼저 취소한다 (마지막 호출이 이긴다). // 취소된 쪽은 아래 finally까지 이 자리에서 정리를 마치고 빠져나간다. CancelPending(); SetQuestion(choiceQuestion); ClearRows(); for (int i = 0; i < choices.Count; i++) { var row = Instantiate(_rowPrefab, _rowContainer); row.Bind(i, DialogVariables.Format(choices[i].ChoiceText)); // {key} 토큰 치환 row.OnClicked += HandleClicked; _rows.Add(row); } ResizeToRowCount(choices.Count); _root.SetActive(true); var completion = new AwaitableCompletionSource(); _completion = completion; int result; try { result = await completion.Awaitable; } finally { // 내가 아직 현재 세션일 때만 정리 — 취소 직후 다른 NPC가 새로 띄운 메뉴를 지우면 안 된다 if (_completion == completion) { _completion = null; Hide(); } } return result; } private void HandleClicked(int index) { _completion?.TrySetResult(index); } // 선택지 개수에 맞춰 스크롤 영역 높이 조절 (1개=40, 2개=80, 3개=120 …). // _maxVisibleRows를 넘는 개수는 높이를 더 늘리지 않고 스크롤로 본다. private void ResizeToRowCount(int count) { if (_ScrollRect == null) return; int visibleRows = Mathf.Min(count, _maxVisibleRows); _ScrollRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, visibleRows * _rowHeight); } private void Hide() { SetQuestion(null); ClearRows(); if (_root != null) _root.SetActive(false); } // 질문이 비어 있으면 질문 텍스트 자체를 숨긴다. (기본값: 질문 없음 → 안 보임) // 질문은 보통 노드의 대사(TalkText)로 대신하므로 ChoiceQuestion은 비워둬도 된다. private void SetQuestion(string question) { if (ChoiceQuestion == null) return; string text = DialogVariables.Format(question); // {key} 토큰 치환 bool hasQuestion = !string.IsNullOrWhiteSpace(text); ChoiceQuestion.text = hasQuestion ? text : string.Empty; ChoiceQuestion.gameObject.SetActive(hasQuestion); } private void ClearRows() { foreach (var row in _rows) { if (row == null) continue; row.OnClicked -= HandleClicked; Destroy(row.gameObject); } _rows.Clear(); } }