Files
FueraDeEscala/Assets/Game/Menus/LoadingScreen/LoadingScreenController.cs

85 lines
2.8 KiB
C#
Raw Normal View History

using UnityEngine;
using UnityEngine.UIElements;
using UnityEngine.SceneManagement;
using System.Collections;
public class LoadingScreenController : MonoBehaviour
{
private UIDocument _doc;
private Label _loadingText;
private VisualElement _spaceship;
private int _dotCount = 0;
private float _time = 0f;
[Header("Configuración de Carga")]
public string sceneToLoad = "SampleScene";
private void Awake()
{
_doc = GetComponent<UIDocument>();
var root = _doc.rootVisualElement;
// Forzar que el TemplateContainer raíz ocupe toda la pantalla
root.style.flexGrow = 1;
root.style.width = new Length(100, LengthUnit.Percent);
root.style.height = new Length(100, LengthUnit.Percent);
_loadingText = root.Q<Label>("LoadingText");
_spaceship = root.Q<VisualElement>("Spaceship");
// 1. Animación del texto: Se ejecuta cada 400 milisegundos
root.schedule.Execute(UpdateLoadingText).Every(400);
// 2. Animación loca de la nave: Se ejecuta cada 20 milisegundos para fluidez
root.schedule.Execute(AnimateSpaceship).Every(20);
// 3. Iniciar la carga de la escena en segundo plano
StartCoroutine(LoadSceneAsync());
}
private void UpdateLoadingText()
{
// Alterna entre 0 y 3 puntos
_dotCount = (_dotCount + 1) % 4;
_loadingText.text = "Cargando" + new string('.', _dotCount);
}
private void AnimateSpaceship()
{
if (_spaceship == null) return;
_time += 0.1f;
// Efecto "Rabbid": vibración y rotación errática usando Seno y Coseno
float offsetX = Mathf.Sin(_time * 12f) * 8f;
float offsetY = Mathf.Cos(_time * 15f) * 6f;
float rotation = Mathf.Sin(_time * 20f) * 3f;
_spaceship.style.translate = new Translate(offsetX, offsetY, 0);
_spaceship.style.rotate = new Rotate(new Angle(rotation, AngleUnit.Degree));
}
private IEnumerator LoadSceneAsync()
{
// Pequeña pausa opcional para que la pantalla no parpadee si la escena carga muy rápido
yield return new WaitForSeconds(0.5f);
AsyncOperation asyncLoad = SceneManager.LoadSceneAsync(sceneToLoad);
// La escena no cambia automáticamente hasta que nosotros lo indiquemos
asyncLoad.allowSceneActivation = false;
// Espera hasta que Unity haya cargado el 90% (el 10% restante es la activación)
while (asyncLoad.progress < 0.9f)
{
yield return null;
}
// Pequeña pausa para que la animación sea visible aunque la escena cargue muy rápido
yield return new WaitForSeconds(0.8f);
// Ahora sí, activa la escena
asyncLoad.allowSceneActivation = true;
}
}