| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124 |
- using UnityEngine;
- using UnityEngine.SceneManagement;
- using UnityEngine.UI;
- using TMPro;
- using System.Collections;
- public class LoadingManager : MonoBehaviour
- {
- public static string sceneToLoad;
- [Header("UI")]
- public TMP_Text continueText;
- public Image progressFill;
- public float minimumLoadTime = 2f;
- public TMP_Text tipText;
- [Header("Tips")]
- [TextArea(2, 4)]
- public string[] tips;
- public static bool loadSave = false;
- void Start()
- {
- StartCoroutine(LoadAsync());
- }
- void Update()
- {
- if (progressFill != null)
- progressFill.fillAmount = Mathf.PingPong(Time.time, 1f);
- }
- IEnumerator LoadAsync()
- {
- AsyncOperation operation =
- SceneManager.LoadSceneAsync(sceneToLoad);
- operation.allowSceneActivation = false;
- float displayedProgress = 0f;
- if (continueText != null)
- continueText.gameObject.SetActive(false);
- // Show a random tip on-screen
- if (tips.Length > 0 && tipText != null)
- {
- int randomIndex = Random.Range(0, tips.Length);
- tipText.text = "Tip: \n" + tips[randomIndex];
- }
- // Minimum load time
- float timer = 0f;
- while (!operation.isDone)
- {
- timer += Time.deltaTime;
- // Smooth fill through bar
- float targetProgress = Mathf.Clamp01(operation.progress / 0.9f);
- displayedProgress = Mathf.MoveTowards(displayedProgress, targetProgress, Time.deltaTime * 0.5f);
- if (progressFill != null)
- progressFill.fillAmount = displayedProgress;
- // Show continue text when fully loaded
- if (displayedProgress >= 1f && timer >= minimumLoadTime)
- {
- if (continueText != null)
- continueText.gameObject.SetActive(true);
- // Wait for any key press
- if (Input.anyKeyDown)
- {
- operation.allowSceneActivation = true;
- }
- }
- yield return null;
- }
- // Wait one frame for GameManager to Awake
- yield return null;
- if (loadSave)
- {
- SaveData data = SaveSystem.Load(); // load JSON file
- if (data != null)
- {
- // Wait one frame to ensure GameManager is awake
- yield return null;
- if (GameManager.Instance != null)
- {
- GameManager.Instance.LoadGame(data);
- }
- else
- {
- Debug.LogWarning("No GameManager found! Starting new game.");
- }
- }
- else
- {
- Debug.LogWarning("No save file found! Starting new game.");
- GameManager.Instance.StartNewGame();
- }
- }
- else
- {
- GameManager.Instance.StartNewGame();
- }
- }
- public static SaveData currentSave;
- }
|