115 lines
2.8 KiB
C#

using System;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
public class DialogueUI : MonoBehaviour
{
[Header("References")]
public CanvasGroup root; // Whole dialogue panel
public TMP_Text speakerNameText;
public Image speakerPortraitImage;
public TMP_Text bodyText;
[Header("Choices")]
public Transform choicesParent;
public Button choiceButtonPrefab;
[Header("Typing")]
[Range(0.005f, 0.1f)] public float charDelay = 0.02f;
string _targetFull;
bool _completeThisFrame;
void Reset()
{
root = GetComponent<CanvasGroup>();
}
public void Show(bool on)
{
if (!root) return;
root.alpha = on ? 1f : 0f;
root.interactable = on;
root.blocksRaycasts = on;
if (!on)
{
bodyText?.SetText(string.Empty);
HideChoices();
}
}
public void BindSpeaker(string speakerName, Sprite portrait)
{
if (speakerNameText) speakerNameText.text = speakerName ?? "";
if (speakerPortraitImage)
{
speakerPortraitImage.sprite = portrait;
speakerPortraitImage.enabled = portrait != null;
}
}
public IEnumerator TypeText(string text)
{
_targetFull = text ?? string.Empty;
bodyText.text = string.Empty;
_completeThisFrame = false;
foreach (char c in _targetFull)
{
if (_completeThisFrame) break;
bodyText.text += c;
yield return new WaitForSeconds(charDelay);
}
bodyText.text = _targetFull;
_completeThisFrame = false;
}
public void CompleteTypeThisFrame()
{
_completeThisFrame = true;
}
public List<DialogueAsset.Choice> BuildVisibleChoices(
List<DialogueAsset.Choice> all,
HashSet<string> flags)
{
var list = new List<DialogueAsset.Choice>();
if (all == null) return list;
foreach (var c in all)
{
if (string.IsNullOrEmpty(c.requireFlag) || flags.Contains(c.requireFlag))
list.Add(c);
}
return list;
}
public void ShowChoices(
List<DialogueAsset.Choice> choices,
Action<DialogueAsset.Choice> onPick)
{
HideChoices();
foreach (var c in choices)
{
var btn = Instantiate(choiceButtonPrefab, choicesParent);
var label = btn.GetComponentInChildren<TMP_Text>();
if (label) label.text = c.text;
btn.onClick.AddListener(() => onPick?.Invoke(c));
}
}
public void HideChoices()
{
if (!choicesParent) return;
for (int i = choicesParent.childCount - 1; i >= 0; i--)
Destroy(choicesParent.GetChild(i).gameObject);
}
}