using System.Collections; using TMPro; using UnityEngine; [DisallowMultipleComponent] public class ToastView : MonoBehaviour { [SerializeField] CanvasGroup canvasGroup; [SerializeField] TMP_Text label; [SerializeField] float fadeInDuration = 0.12f; [SerializeField] float fadeOutDuration = 0.22f; Coroutine routine; void Awake() { if (canvasGroup == null) canvasGroup = GetComponent(); if (label == null) label = GetComponentInChildren(true); if (canvasGroup != null) { canvasGroup.alpha = 0f; canvasGroup.interactable = false; canvasGroup.blocksRaycasts = false; } } public void Show(string message, float holdDuration = 1.9f) { if (string.IsNullOrEmpty(message)) return; gameObject.SetActive(true); transform.SetAsLastSibling(); if (label != null) label.text = message; if (routine != null) StopCoroutine(routine); routine = StartCoroutine(Run(message, holdDuration)); } public void HideImmediate() { if (routine != null) { StopCoroutine(routine); routine = null; } if (canvasGroup != null) canvasGroup.alpha = 0f; gameObject.SetActive(false); } IEnumerator Run(string message, float holdDuration) { if (label != null) label.text = message; if (canvasGroup == null) { yield return new WaitForSecondsRealtime(holdDuration); gameObject.SetActive(false); yield break; } float elapsed = 0f; while (elapsed < fadeInDuration) { elapsed += Time.unscaledDeltaTime; canvasGroup.alpha = Mathf.Clamp01(elapsed / fadeInDuration); yield return null; } canvasGroup.alpha = 1f; if (holdDuration > 0f) yield return new WaitForSecondsRealtime(holdDuration); elapsed = 0f; while (elapsed < fadeOutDuration) { elapsed += Time.unscaledDeltaTime; canvasGroup.alpha = 1f - Mathf.Clamp01(elapsed / fadeOutDuration); yield return null; } canvasGroup.alpha = 0f; routine = null; gameObject.SetActive(false); } }