Files
Fruitomation/Assets/Scripts/Game/SceneController.cs
2026-04-13 21:23:26 +01:00

80 lines
2.4 KiB
C#

using PashaBibko.Pacore.Attributes;
using UnityEngine.SceneManagement;
using System.Collections;
using UnityEngine;
using System;
using Debug = UnityEngine.Debug;
namespace Fruitomation.Game
{
[CreateInstanceOnStart] public class SceneController : MonoBehaviour
{
private SceneControllerTransition Transition;
private static SceneController Instance;
private void Awake()
{
if (Instance is not null)
{
Debug.LogError($"Multiple instances of [{nameof(SceneController)}] cannot exist.");
return;
}
Instance = this;
Canvas canvas = gameObject.AddComponent<Canvas>();
canvas.renderMode = RenderMode.ScreenSpaceOverlay;
GameObject overlayGo = new("Overlay");
overlayGo.transform.SetParent(canvas.transform);
Transition = overlayGo.AddComponent<SceneControllerTransition>();
Transition.OnCreation(canvas);
}
private IEnumerator StartLoadInternal(string scene)
{
AsyncOperation operation = SceneManager.LoadSceneAsync(scene);
if (operation == null)
{
string error = $"Unknown scene [{scene}]";
throw new ArgumentException(error);
}
operation.allowSceneActivation = false;
operation.completed += _ => StartCoroutine(EndLoadInternal());
Transition.GoingUp = false;
Time.timeScale = 0;
float lerp = 0f;
while (lerp < 1f)
{
lerp += Time.unscaledDeltaTime;
Transition.LerpValue = Mathf.Clamp01(lerp);
yield return null; // Waits for next frame
}
operation.allowSceneActivation = true;
}
private IEnumerator EndLoadInternal()
{
float lerp = 0f;
while (lerp < 1f)
{
lerp += Time.unscaledDeltaTime;
Transition.LerpValue = Mathf.Clamp01(lerp);
yield return null; // Waits for next frame
}
Time.timeScale = 1f;
}
public static void StartLoadOf(string scene) => Instance.StartCoroutine(Instance.StartLoadInternal(scene));
}
}