Files
monde-usage-unity/Assets/Scripts/UI/LoadingScreen.cs
2024-10-02 22:32:02 +02:00

88 lines
2.3 KiBLFS
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class LoadingScreen : MonoBehaviour
{
private string text = "Chargement des videos";
[SerializeField] private TMPro.TextMeshProUGUI loadingText;
[SerializeField] private Slider loadingBar;
[SerializeField] private TMPro.TextMeshProUGUI loadingBarText;
[SerializeField] private float loadingBarSpeed = 1;
[SerializeField] private float hideAtPercent = 0.3f;
private float loadingBarValue = 0;
void Start()
{
loadingBar.gameObject.SetActive(false);
loadingBar.value = 0;
loadingBarText.text = "";
}
void Update()
{
loadingBar.value = loadingBarValue;
}
IEnumerator ShowLoadingScreen()
{
float delay = 0.4f;
while (true)
{
loadingText.text = text;
yield return new WaitForSeconds(delay);
loadingText.text = text + ".";
yield return new WaitForSeconds(delay);
loadingText.text = text + "..";
yield return new WaitForSeconds(delay);
loadingText.text = text + "...";
yield return new WaitForSeconds(delay);
}
}
IEnumerator SmoothLoadingBar()
{
while (true)
{
loadingBarValue = Mathf.Lerp(loadingBarValue, loadingBar.value, Time.deltaTime * loadingBarSpeed);
yield return null;
}
}
public void Show(int total)
{
gameObject.SetActive(true);
StartCoroutine(ShowLoadingScreen());
StartCoroutine(SmoothLoadingBar());
loadingBarValue = 0;
loadingBarText.text = "0 / " + total;
}
public void Hide()
{
StopAllCoroutines();
gameObject.SetActive(false);
}
private int TotalVideos => GameManager.singleton.VideoDownloader.VideoAssets.Count;
public void ProgressCallback(int current, int total)
{
if (!gameObject.activeSelf) return;
loadingBar.gameObject.SetActive(true);
float progress = (float)current / total;
loadingBarValue = progress;
loadingBarText.text = $"{current} / {TotalVideos}";
Debug.Log($"Progress: {progress} ({current} / {total}) percentAt: {hideAtPercent}");
if (progress > hideAtPercent)
{
Hide();
}
}
}