using System.Collections.Generic; using UnityEngine; using UnityEngine.UIElements; // "어떤 대화를 걸지" 고르는 메뉴 (역전재판식 "대화하기" — 후보가 여럿이면 골라서 시작). // DialogEnterUI.uxml의 ListView로 후보를 띄우고, 행을 클릭하면 그 인덱스를 반환한다. // 대사 도중의 분기 선택지(ChoiceHud)와는 별개다 — 이건 대화를 시작하기 전 단계의 UI. // DialogPlayer.SelectBeat가 재생 가능한 비트가 여럿일 때 사용한다. [RequireComponent(typeof(UIDocument))] public class DialogEnterHud : MonoBehaviour { public static DialogEnterHud Instance { get; private set; } private UIDocument _document; private VisualElement _root; // 전체 토글 대상(#Body) private ListView _listView; private bool _ready; private List _options; private AwaitableCompletionSource _completion; private void Awake() { if (Instance != null && Instance != this) { Destroy(gameObject); return; } Instance = this; _document = GetComponent(); } private void Start() => Hide(); private void OnDestroy() { if (Instance == this) Instance = null; } private void OnDisable() { // 씬 전환 등으로 비활성화될 때 진행 중 대기 정리 _completion?.TrySetCanceled(); _completion = null; } // rootVisualElement가 준비된 뒤 한 번만 요소를 캐싱하고 ListView 콜백을 건다. private bool EnsureRefs() { if (_ready) return true; var root = _document != null ? _document.rootVisualElement : null; if (root == null) return false; _root = root.Q("Body"); _listView = root.Q(); if (_listView != null) { _listView.selectionType = SelectionType.Single; _listView.bindItem = BindRow; // item-template(DialogEnterRow)이 makeItem을 담당, 바인딩만 우리가 _listView.selectionChanged += OnSelectionChanged; } _ready = true; return true; } // 대기 중인 선택을 취소하고 메뉴를 닫는다 (다른 NPC와 대화를 새로 시작할 때 등). // 취소된 쪽의 await Show(...)는 OperationCanceledException으로 빠져나간다. public void CancelPending() => _completion?.TrySetCanceled(); // 후보 목록을 띄우고 고른 인덱스를 반환한다. 취소되면 OperationCanceledException. public async Awaitable Show(List options) { if (options == null || options.Count == 0) return 0; if (!EnsureRefs()) return 0; // 이전 호출이 아직 대기 중이면 먼저 취소한다 (마지막 호출이 이긴다). CancelPending(); _options = options; _listView.itemsSource = options; _listView.ClearSelection(); _listView.Rebuild(); _root.style.display = DisplayStyle.Flex; var completion = new AwaitableCompletionSource(); _completion = completion; int result; try { result = await completion.Awaitable; } finally { // 내가 아직 현재 세션일 때만 정리 — 취소 직후 다른 NPC가 새로 띄운 메뉴를 지우면 안 된다 if (_completion == completion) { _completion = null; Hide(); } } return result; } // ListView 행(item-template = DialogEnterRow.uxml)에 후보 이름을 채운다. // 행 템플릿의 Label엔 name이 없어 타입으로 찾는다. private void BindRow(VisualElement element, int i) { var label = element.Q