Files
XRLib/Assets/Scripts/UVC/UI/Loading/UILoading.cs

104 lines
2.7 KiB
C#
Raw Normal View History

2025-07-22 19:58:14 +09:00
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();
}
}
2025-07-24 18:28:09 +09:00
[SerializeField]
2025-07-22 19:58:14 +09:00
private CanvasGroup canvasGroup;
2025-07-24 18:28:09 +09:00
[SerializeField]
private Image loadinImage;
2025-07-22 19:58:14 +09:00
private float duration = 0.25f;
2025-07-24 18:28:09 +09:00
private float target = 0;
2025-07-22 19:58:14 +09:00
private float alpha = 1;
private bool animatting = false;
private Transform loadingImageTransform;
private float loadingSpeed = 1.5f;
2025-07-24 18:28:09 +09:00
private float rotationSpeed = -1.0f;
2025-07-22 19:58:14 +09:00
private void Awake()
2025-07-24 18:28:09 +09:00
{
2025-07-22 19:58:14 +09:00
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);
}
}
}
}