108 lines
3.2 KiB
C#
108 lines
3.2 KiB
C#
using System.Collections;
|
|
using TMPro;
|
|
using UnityEngine;
|
|
using UVC.Core;
|
|
using UVC.Util;
|
|
|
|
namespace UVC.UI.Modal
|
|
{
|
|
public class Toast : SingletonApp<Toast>
|
|
{
|
|
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>();
|
|
toast.change(0);
|
|
}
|
|
if (toast != null)
|
|
{
|
|
toast.gameObject.SetActive(true);
|
|
Canvas canvas = CanvasUtil.GetOrCreate("ModalCanvas");
|
|
toast.transform.SetParent(canvas.transform);
|
|
toast.show(message, duration, fadeInOutTime);
|
|
}
|
|
}
|
|
|
|
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<TextMeshProUGUI>();
|
|
fitTextWidth(GetComponent<RectTransform>(), 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>();
|
|
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);
|
|
|
|
|
|
}
|
|
|
|
}
|
|
}
|