using System; using System.Collections; using System.Collections.Generic; using System.Text; using UnityEngine; using UnityEngine.Events; public class UITextShow : MonoBehaviour { private TMPro.TextMeshProUGUI _text; private Coroutine coroutine; public UnityEvent OnTimeTick; public UnityEvent OnTimeEnd; public string Prefix; public string Postfix; public string Text => _text.text; private void Awake() { _text = GetComponent(); } public void SetText(string text) { _text.SetText($"{Prefix}{text}{Postfix}"); _text.SetAllDirty(); } public void SetText(int num) { SetText(num.ToString()); } public void SetText(string text, float afterDelay, Action onStart, Action onEnd) { if (coroutine != null) { StopCoroutine(coroutine); } coroutine = StartCoroutine(SetText_Coroutine(text, afterDelay, onStart, onEnd)); } public void ShowSubtitle(string text, float delay, float afterDelay, Action onStart, Action onEnd) { if (coroutine != null) { StopCoroutine(coroutine); } coroutine = StartCoroutine(Subtitle_Coroutine(text, delay, afterDelay, onStart, onEnd)); } public void ShowTimer(int time, string afterTimerText, float afterDelay, Action onStart, Action onEnd) { if (coroutine != null) { StopCoroutine(coroutine); } StartCoroutine(Timer_Coroutine(time, afterTimerText, afterDelay, onStart, onEnd)); } private IEnumerator Timer_Coroutine(int time, string afterTimerText, float afterDelay, Action onStart, Action onEnd) { onStart?.Invoke(); for (int i = time; i > 0; i--) { SetText(i.ToString()); OnTimeTick?.Invoke(); yield return new WaitForSeconds(1); } SetText(afterTimerText); yield return new WaitForSeconds(afterDelay); //_text.SetText(string.Empty); OnTimeEnd?.Invoke(); onEnd?.Invoke(); } private IEnumerator Subtitle_Coroutine(string text, float delay, float afterDelay, Action onStart, Action onEnd) { onStart?.Invoke(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < text.Length; i++) { sb.Append(text[i]); SetText(sb.ToString()); OnTimeTick?.Invoke(); yield return new WaitForSeconds(delay); } yield return new WaitForSeconds(afterDelay); SetText(string.Empty); OnTimeEnd?.Invoke(); onEnd?.Invoke(); } private IEnumerator SetText_Coroutine(string text, float afterDelay, Action onStart, Action onEnd) { onStart?.Invoke(); SetText(text); yield return new WaitForSeconds(afterDelay); SetText(string.Empty); OnTimeEnd?.Invoke(); onEnd?.Invoke(); } }