72 lines
2.2 KiB
C#

using System.Collections;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.UIElements;
namespace Management
{
/// <summary>
/// Global access pattern for services.
/// If you need a component or some data that needs to be used in many places, here's a good spot.
/// </summary>
public class Services : MonoBehaviour
{
// Enforce singleton pattern
public static Services Instance { get; private set; }
// BGM service for playing/changing background music.
public BGM BGM => bgm;
// SFX service to serve as single spot SFX plays from.
public SFX SFX => sfx;
public InputRouter InputRouter => inputRouter;
[SerializeField] private BGM bgm;
[SerializeField] private SFX sfx;
[SerializeField] private InputRouter inputRouter;
[SerializeField] private GameObject transition;
[SerializeField] private float transitionTime;
private Coroutine _transitionRoutine;
private VisualElement _loadingScreen;
public void ShowTransition(bool show)
{
if (_transitionRoutine != null)
StopCoroutine(_transitionRoutine);
_transitionRoutine = StartCoroutine(TransitionRoutine(!show));
}
private IEnumerator TransitionRoutine(bool reverse)
{
var timer = 0f;
while (timer < transitionTime)
{
timer += Time.deltaTime;
_loadingScreen.style.opacity = Mathf.Lerp(
reverse ? 1 : 0,
reverse ? 0: 1, timer / transitionTime);
yield return null;
}
_transitionRoutine = null;
}
private void Awake()
{
// enforce singleton
if (Instance != null && Instance != this)
{
Destroy(gameObject);
return;
}
Instance = this;
// survive scene reloads
DontDestroyOnLoad(gameObject);
_loadingScreen = transition.GetComponent<UIDocument>().rootVisualElement.Q<VisualElement>("transitionContainer");
}
}
}