BITFALL/Assets/BITKit/Unity/Scripts/Scenes/UX/UXSceneLoading.cs

80 lines
1.9 KiB
C#

using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using BITKit.UX;
using UnityEngine;
using Cysharp.Threading.Tasks;
using System.Threading.Tasks;
using Task = System.Threading.Tasks.Task;
// ReSharper disable Unity.NoNullPropagation
namespace BITKit.SceneManagement.UX
{
public class UXSceneLoading : MonoBehaviour
{
[Header(Constant.Header.Settings)]
[SerializeReference, SubclassSelector] private ISceneService sceneService;
[SerializeField] private float fadeOutTime = 0.5f;
[SerializeField] private UXLabel sceneNameLabel;
[SerializeField] private UXBar loadingBar;
[SerializeField] private UXElement backgroundImage;
[SerializeField] private bool autoDestroyAfterLoaded;
protected float _progress;
protected float _currentProgress;
private CancellationToken _cancellationToken;
private void Awake()
{
_cancellationToken = gameObject.GetCancellationTokenOnDestroy();
}
private void Start()
{
sceneService.OnLoadScene += OnLoadScene;
sceneService.OnSceneLoadProgress+=OnSceneLoadProgress;
sceneService.OnSceneLoaded += OnSceneLoaded;
}
private void Update()
{
_currentProgress = Mathf.Lerp(_currentProgress, _progress, Time.deltaTime * 10);
loadingBar?.Set(_currentProgress);
}
private void OnDestroy()
{
sceneService.OnLoadScene -= OnLoadScene;
sceneService.OnSceneLoadProgress-=OnSceneLoadProgress;
sceneService.OnSceneLoaded -= OnSceneLoaded;
}
private void OnSceneLoadProgress(string arg1, float arg2)
{
_progress = arg2;
}
private void OnLoadScene(string obj)
{
sceneNameLabel?.Set(obj);
}
private async void OnSceneLoaded(string obj)
{
if(autoDestroyAfterLoaded is false)return;
backgroundImage.SetActive(false);
try
{
await Task.Delay(TimeSpan.FromSeconds(fadeOutTime),_cancellationToken);
Destroy(gameObject);
}
catch (OperationCanceledException)
{
}
}
}
}