105 lines
2.8 KiB
C#
105 lines
2.8 KiB
C#
|
|
using System.Collections;
|
||
|
|
using UnityEngine;
|
||
|
|
using UnityEngine.UI;
|
||
|
|
|
||
|
|
namespace UVC.UI.Loading
|
||
|
|
{
|
||
|
|
[RequireComponent(typeof(CanvasGroup))]
|
||
|
|
public class UILoading : UnityEngine.MonoBehaviour
|
||
|
|
{
|
||
|
|
public static string PrefabPath = "Prefabs/UI/Loading/UILoading";
|
||
|
|
|
||
|
|
private static UILoading instance;
|
||
|
|
|
||
|
|
public static void Show()
|
||
|
|
{
|
||
|
|
if (instance == null) {
|
||
|
|
GameObject prefab = Resources.Load<GameObject>(PrefabPath);
|
||
|
|
GameObject go = Instantiate(prefab);
|
||
|
|
go.name = "UILoading";
|
||
|
|
go.transform.SetParent(null, false);
|
||
|
|
instance = go.GetComponent<UILoading>();
|
||
|
|
}
|
||
|
|
instance.ShowLoading();
|
||
|
|
}
|
||
|
|
|
||
|
|
public static void Hide()
|
||
|
|
{
|
||
|
|
if (instance != null)
|
||
|
|
{
|
||
|
|
instance.HideLoading();
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
|
||
|
|
private CanvasGroup canvasGroup;
|
||
|
|
private float target = 0;
|
||
|
|
private float duration = 0.25f;
|
||
|
|
private float alpha = 1;
|
||
|
|
private bool animatting = false;
|
||
|
|
private Image loadinImage;
|
||
|
|
private Transform loadingImageTransform;
|
||
|
|
|
||
|
|
private float loadingSpeed = 1.5f;
|
||
|
|
private float rotationSpeed = 1.0f;
|
||
|
|
|
||
|
|
private void Awake()
|
||
|
|
{
|
||
|
|
canvasGroup = GetComponent<CanvasGroup>();
|
||
|
|
loadinImage = transform.Find("loadingImage").GetComponent<Image>();
|
||
|
|
loadingImageTransform = loadinImage.transform;
|
||
|
|
|
||
|
|
}
|
||
|
|
|
||
|
|
|
||
|
|
public void ShowLoading()
|
||
|
|
{
|
||
|
|
if (animatting && target == 1) return;
|
||
|
|
|
||
|
|
target = 1;
|
||
|
|
animatting = true;
|
||
|
|
StopCoroutine("Animate");
|
||
|
|
StartCoroutine(Animate());
|
||
|
|
}
|
||
|
|
|
||
|
|
public void HideLoading()
|
||
|
|
{
|
||
|
|
if (animatting && target == 0) return;
|
||
|
|
|
||
|
|
target = 0;
|
||
|
|
animatting = true;
|
||
|
|
StopCoroutine("Animate");
|
||
|
|
StartCoroutine(Animate());
|
||
|
|
}
|
||
|
|
|
||
|
|
private IEnumerator Animate()
|
||
|
|
{
|
||
|
|
float start = canvasGroup.alpha;
|
||
|
|
float time = 0;
|
||
|
|
|
||
|
|
while (time < duration)
|
||
|
|
{
|
||
|
|
time += Time.deltaTime;
|
||
|
|
canvasGroup.alpha = Mathf.Lerp(start, target, time / duration);
|
||
|
|
yield return null;
|
||
|
|
}
|
||
|
|
|
||
|
|
canvasGroup.alpha = target;
|
||
|
|
animatting = false;
|
||
|
|
if(target == 0)
|
||
|
|
{
|
||
|
|
Destroy(gameObject);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
private void Update()
|
||
|
|
{
|
||
|
|
if (canvasGroup.alpha == 1)
|
||
|
|
{
|
||
|
|
loadingImageTransform.Rotate(Vector3.forward, loadingSpeed * Time.deltaTime * 360);
|
||
|
|
loadinImage.fillAmount = Mathf.PingPong(Time.time * rotationSpeed, 1);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|