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(PrefabPath); GameObject go = Instantiate(prefab); go.name = "UILoading"; go.transform.SetParent(null, false); instance = go.GetComponent(); } instance.ShowLoading(); } public static void Hide() { if (instance != null) { instance.HideLoading(); } } [SerializeField] private CanvasGroup canvasGroup; [SerializeField] private Image loadinImage; private float duration = 0.25f; private float target = 0; private float alpha = 1; private bool animatting = false; private Transform loadingImageTransform; private float loadingSpeed = -1.5f; private float rotationSpeed = -1.0f; private void Awake() { 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); } } } }