ToastView.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. using System.Collections;
  2. using TMPro;
  3. using UnityEngine;
  4. [DisallowMultipleComponent]
  5. public class ToastView : MonoBehaviour
  6. {
  7. [SerializeField] CanvasGroup canvasGroup;
  8. [SerializeField] TMP_Text label;
  9. [SerializeField] float fadeInDuration = 0.12f;
  10. [SerializeField] float fadeOutDuration = 0.22f;
  11. Coroutine routine;
  12. void Awake()
  13. {
  14. if (canvasGroup == null)
  15. canvasGroup = GetComponent<CanvasGroup>();
  16. if (label == null)
  17. label = GetComponentInChildren<TMP_Text>(true);
  18. if (canvasGroup != null)
  19. {
  20. canvasGroup.alpha = 0f;
  21. canvasGroup.interactable = false;
  22. canvasGroup.blocksRaycasts = false;
  23. }
  24. }
  25. public void Show(string message, float holdDuration = 1.9f)
  26. {
  27. if (string.IsNullOrEmpty(message))
  28. return;
  29. gameObject.SetActive(true);
  30. transform.SetAsLastSibling();
  31. if (label != null)
  32. label.text = message;
  33. if (routine != null)
  34. StopCoroutine(routine);
  35. routine = StartCoroutine(Run(message, holdDuration));
  36. }
  37. public void HideImmediate()
  38. {
  39. if (routine != null)
  40. {
  41. StopCoroutine(routine);
  42. routine = null;
  43. }
  44. if (canvasGroup != null)
  45. canvasGroup.alpha = 0f;
  46. gameObject.SetActive(false);
  47. }
  48. IEnumerator Run(string message, float holdDuration)
  49. {
  50. if (label != null)
  51. label.text = message;
  52. if (canvasGroup == null)
  53. {
  54. yield return new WaitForSecondsRealtime(holdDuration);
  55. gameObject.SetActive(false);
  56. yield break;
  57. }
  58. float elapsed = 0f;
  59. while (elapsed < fadeInDuration)
  60. {
  61. elapsed += Time.unscaledDeltaTime;
  62. canvasGroup.alpha = Mathf.Clamp01(elapsed / fadeInDuration);
  63. yield return null;
  64. }
  65. canvasGroup.alpha = 1f;
  66. if (holdDuration > 0f)
  67. yield return new WaitForSecondsRealtime(holdDuration);
  68. elapsed = 0f;
  69. while (elapsed < fadeOutDuration)
  70. {
  71. elapsed += Time.unscaledDeltaTime;
  72. canvasGroup.alpha = 1f - Mathf.Clamp01(elapsed / fadeOutDuration);
  73. yield return null;
  74. }
  75. canvasGroup.alpha = 0f;
  76. routine = null;
  77. gameObject.SetActive(false);
  78. }
  79. }