| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899 |
- 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<CanvasGroup>();
- if (label == null)
- label = GetComponentInChildren<TMP_Text>(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);
- }
- }
|