Files
bansonic_beta_main/Assets/scripts/BootLoader.cs
T
2026-06-30 21:21:30 +08:00

101 lines
2.9 KiB
C#

using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using Bansonic;
public class BootLoader : MonoBehaviour
{
[Header("Settings")]
[Tooltip("The name of the main scene to load asynchronously.")]
[SerializeField] private string mainSceneName = "Main_main";
[Tooltip("Minimum time to show the splash screen (in seconds).")]
[SerializeField] private float minSplashTime = 2.0f;
[Header("UI References")]
[Tooltip("Optional Slider to show loading progress.")]
[SerializeField] private Slider progressSlider;
[Tooltip("Optional Text to show loading percentage.")]
[SerializeField] private Text progressText;
private bool transitionStarted;
private void Start()
{
// Start the asynchronous loading process
StartCoroutine(LoadMainSceneAsync());
}
private IEnumerator LoadMainSceneAsync()
{
// Prevent the screen from sleeping during loading
Screen.sleepTimeout = SleepTimeout.NeverSleep;
float startTime = Time.time;
// Start loading the scene asynchronously
AsyncOperation asyncLoad = SceneManager.LoadSceneAsync(mainSceneName);
// Prevent the scene from activating immediately
asyncLoad.allowSceneActivation = false;
while (!asyncLoad.isDone)
{
// Calculate progress (0.0 to 0.9)
float progress = Mathf.Clamp01(asyncLoad.progress / 0.9f);
// Update UI if references are assigned
if (progressSlider != null)
{
progressSlider.value = progress;
}
if (progressText != null)
{
progressText.text = $"{(progress * 100):0}%";
}
// Check if loading is complete (progress >= 0.9) and minimum time has passed
if (asyncLoad.progress >= 0.9f)
{
// Wait for the minimum splash time
float elapsedTime = Time.time - startTime;
if (elapsedTime >= minSplashTime)
{
if (!transitionStarted)
{
transitionStarted = true;
if (gTransition.Run(AllowSceneActivationRoutine(asyncLoad)))
{
yield break;
}
asyncLoad.allowSceneActivation = true;
}
}
}
yield return null;
}
// Restore screen sleep timeout
Screen.sleepTimeout = SleepTimeout.SystemSetting;
}
private IEnumerator AllowSceneActivationRoutine(AsyncOperation asyncLoad)
{
if (asyncLoad == null)
{
yield break;
}
asyncLoad.allowSceneActivation = true;
while (!asyncLoad.isDone)
{
yield return null;
}
}
}