using System.Collections; using TMPro; using UnityEngine; using UVC.Core; namespace UVC.UI.Modal { public class Toast : SingletonApp { protected static string prefabPath = "Prefabs/UI/Modal/Toast"; protected static GameObject prefab; protected static Toast toast; public static void Show(string message, float duration = 3f, float fadeInOutTime = 0.25f) { if (prefab == null) prefab = Resources.Load(prefabPath, typeof(GameObject)) as GameObject; if (prefab != null && toast == null) { GameObject go = UnityEngine.Object.Instantiate(prefab); toast = go.GetComponent(); toast.change(0); } if (toast != null) { toast.gameObject.SetActive(true); var canvass = GameObject.FindObjectsByType(FindObjectsSortMode.None); Canvas canvas = null; foreach (var c in canvass) { if (c.tag == "ModalCanvas") { canvas = c; toast.transform.SetParent(canvas.transform); toast.show(message, duration, fadeInOutTime); break; } } } } protected CanvasGroup canvasGroup; protected TextMeshProUGUI txt; protected void show(string message, float duration = 3, float fadeInOutTime = 0.25f) { StopAllCoroutines(); StartCoroutine(showCoroutine(message, duration, fadeInOutTime)); } protected IEnumerator showCoroutine(string message, float duration = 3, float fadeInOutTime = 0.25f) { if (txt == null) txt = GetComponentInChildren(); fitTextWidth(GetComponent(), txt, message); yield return fadeInOut(fadeInOutTime, true); change(1); float elapsedTime = 0.0f; while (elapsedTime < duration) { elapsedTime += Time.deltaTime; yield return null; } yield return fadeInOut(fadeInOutTime, false); change(0); transform.SetParent(null); gameObject.SetActive(true); } protected IEnumerator fadeInOut(float durationTime, bool inOut) { float start = 0.0f; float end = 1.0f; if (!inOut) { start = 1.0f; end = 0.0f; } float elapsedTime = 0.0f; while (elapsedTime < durationTime) { float alpha = Mathf.Lerp(start, end, elapsedTime / durationTime); change(alpha); elapsedTime += Time.deltaTime; yield return null; } } protected void change(float alpha) { if (canvasGroup == null) canvasGroup = GetComponent(); canvasGroup.alpha = alpha; } private void fitTextWidth(RectTransform rect, TextMeshProUGUI text, string textValue) { text.text = textValue; Vector2 rectSize = rect.sizeDelta; rectSize.x = text.preferredWidth + 20; rect.sizeDelta = rectSize; rect.anchoredPosition = new Vector2(0, rectSize.y + 10); } } }