using System.Collections.Generic; using TMPro; using UnityEngine; // World-space 선택지 UI 싱글턴. // DialogPlayer가 Show()를 await해서 선택된 인덱스를 받아감. // 배치(Placement)는 DialogHud가 담당하므로, 이 오브젝트를 DialogHud의 자식으로 두면 함께 따라온다. 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 TMP_Text ChoiceQuestion; 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; } public async Awaitable Show(string choiceQuestion, List choices) { if (choices == null || choices.Count == 0) return 0; SetQuestion(choiceQuestion); ClearRows(); for (int i = 0; i < choices.Count; i++) { var row = Instantiate(_rowPrefab, _rowContainer); row.Bind(i, choices[i].ChoiceText); row.OnClicked += HandleClicked; _rows.Add(row); } _root.SetActive(true); _completion = new AwaitableCompletionSource(); int result; try { result = await _completion.Awaitable; } finally { _completion = null; Hide(); } return result; } private void HandleClicked(int index) { _completion?.TrySetResult(index); } private void Hide() { SetQuestion(null); ClearRows(); if (_root != null) _root.SetActive(false); } // 질문이 비어 있으면 질문 텍스트 자체를 숨긴다. (기본값: 질문 없음 → 안 보임) // 질문은 보통 노드의 대사(TalkText)로 대신하므로 ChoiceQuestion은 비워둬도 된다. private void SetQuestion(string question) { if (ChoiceQuestion == null) return; bool hasQuestion = !string.IsNullOrWhiteSpace(question); ChoiceQuestion.text = hasQuestion ? question : 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(); } }