Golf2D/Assets/Scripts/LoadingScreen.cs
2023-05-20 13:49:50 +05:30

89 lines
2.4 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class LoadingScreen : MonoBehaviour
{
public static LoadingScreen instance {get; private set;}
[SerializeField]private Image loadingProgress;
[SerializeField]private Text loadingProgressTxt;
void Awake(){
if(instance != null){Destroy(gameObject);return;}
instance =this;
canvasGroup = GetComponent<CanvasGroup>();
Application.targetFrameRate = 60;
}
void Start()
{
DontDestroyOnLoad(gameObject);
}
public static void LoadLevel(string levelName){
if(instance==null){Debug.LogError("No loading screen found, Raw load"); SceneManager.LoadScene(levelName); return;}
instance.loadLevel(levelName);
}
public void loadLevel(string levelName){
if (loading) { return; }
loading = true;
StartCoroutine(_loadlLevel(levelName));
}
public static bool loading {get; private set;}
private CanvasGroup canvasGroup;
IEnumerator _loadlLevel(string levelName)
{
// AudioManager.instnace.SetMusic(-1);
loading = true;
canvasGroup.alpha = 0;
canvasGroup.blocksRaycasts = true;
SetProgress(0);
while (canvasGroup.alpha < 1f)
{
canvasGroup.alpha += 0.03f;
yield return new WaitForFixedUpdate();
}
AsyncOperation asyncOperation = SceneManager.LoadSceneAsync(levelName);
while (!asyncOperation.isDone)
{
SetProgress(asyncOperation.progress);
yield return null;
}
Debug.Log("Loaded scene " + levelName);
// yield return new WaitForSecondsRealtime(2f);
while(loadingProgress.fillAmount < 1){
SetProgress( loadingProgress.fillAmount+0.01f);
yield return new WaitForSeconds(0.1f);
}
canvasGroup.blocksRaycasts = false;
while (canvasGroup.alpha > 0)
{
canvasGroup.alpha -= 0.03f;
yield return new WaitForSecondsRealtime(0.015f);
}
Debug.Log("Loading scene vanishing");
loading = false;
}
void SetProgress(float value)
{
loadingProgress.fillAmount = value;
loadingProgressTxt.text = (int)(value * 100) + "%";
}
}