87 lines
2.0 KiB
C#
Raw Normal View History

2021-03-25 16:55:36 +08:00
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Toast : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
if (toast!=null)
{
//toast.SetActive(false);
//txt = toast.transform.Find("Toast").GetComponent<Text>();
}
//if (txt != null)
//{
// txt.enabled = false;
//}
}
// Update is called once per frame
void Update()
{
}
[SerializeField] GameObject toast;
[SerializeField] Text txt;
public void showToast(string json)
{
JObject JO = (JObject)JsonConvert.DeserializeObject(json);
2021-04-23 15:36:18 +08:00
gameObject.SetActive(true);
2021-03-25 16:55:36 +08:00
StartCoroutine(showToastCOR(JO.Value<string>("text"), JO.Value<int>("duration")));
}
private IEnumerator showToastCOR(string text,
int duration)
{
2021-04-23 15:36:18 +08:00
gameObject.SetActive(true);
2021-03-25 16:55:36 +08:00
txt.text = text;
//Fade in
yield return fadeInAndOut(txt, true, 0.5f);
//Wait for the duration
float counter = 0;
while (counter < duration)
{
counter += Time.deltaTime;
yield return null;
}
//Fade out
yield return fadeInAndOut(txt, false, 0.5f);
2021-04-23 15:36:18 +08:00
gameObject.SetActive(false);
2021-03-25 16:55:36 +08:00
}
IEnumerator fadeInAndOut(Text targetText, bool fadeIn, float duration)
{
//Set Values depending on if fadeIn or fadeOut
float a, b;
if (fadeIn)
{
a = 0f;
b = 1f;
}
else
{
a = 1f;
b = 0f;
}
float counter = 0f;
while (counter < duration)
{
counter += Time.deltaTime;
float alpha = Mathf.Lerp(a, b, counter / duration);
2021-04-23 15:36:18 +08:00
transform.GetComponent<CanvasGroup>().alpha = alpha;
2021-03-25 16:55:36 +08:00
yield return null;
}
}
}