Files
taptap2024_GJ_chidouren/Assets/Scripts/System/Loader/SceneLoader.cs

109 lines
3.3 KiB
C#
Raw Normal View History

2024-10-16 00:03:41 +08:00
using System;
using Framework.Asset;
using Framework.Timer;
using UnityEngine;
using UnityEngine.SceneManagement;
using YooAsset;
namespace StateSystem.Loader
{
public enum SceneName
{
//初始化入口
InitScene,
//主页面
MainScene,
//游戏场景
GameScene
}
public class SceneLoader : ILoader
{
private readonly string _targetScene;
private SceneHandle _asyncLoader;
private Action _onComplete;
private Action<float> _onLoading;
private TimeHandler _actionTimer;
public bool IsAutoLoad = false;
public SceneLoader (string targetScene)
{
this._targetScene = targetScene;
}
public SceneLoader (SceneName targetScene, bool isAutoLoad = false)
{
this.IsAutoLoad = isAutoLoad;
this._targetScene = AssetManager.ResRootPath + "Scenes/" + targetScene.ToString () + ".unity";
Debug.Log ("准备进入Scene " + this._targetScene);
}
public void BeginLoad (Action<float> onLoading, Action onComplete)
{
this._onLoading = onLoading;
this._onComplete = onComplete;
this._asyncLoader = YooAssets.LoadSceneAsync (this._targetScene , LoadSceneMode.Single);
GameUpdateMgr.Instance.AddUpdater (OnUpdate);
}
public void Active ()
{
Debug.Log ("ActiveScene");
GameUpdateMgr.Instance.RemoveUpdater (OnUpdate);
//最大超时3s后强制回调场景进入完成 若期间_asyncLoader.progress >= 1 则表示已经进入场景
this._actionTimer = GameUpdateMgr.Instance.CreateTimer (3, OnActive, CheckActiveState);
this._asyncLoader.ActivateScene ();
}
private void CheckActiveState (float obj)
{
if (this._asyncLoader.Progress >= 1)
{
this._actionTimer.Kill ();
OnActive ();
}
}
private void OnActive ()
{
var onComplete = this._onComplete;
this._onComplete = null;
onComplete?.Invoke ();
}
private void OnUpdate ()
{
//Unity的异步加载在90%的时候会自动停止除非开启自动跳转才会加载后续部分因此在加载到90%时判断加载完成即可。
var percent = this._asyncLoader.Progress;
// Debug.Log("加载进度: " + percent);
if (percent >= 0.9f)
{
GameUpdateMgr.Instance.RemoveUpdater (OnUpdate);
this._onLoading?.Invoke (1);
if (this.IsAutoLoad)
{
Active ();
}
}
else
{
this._onLoading?.Invoke (percent);
}
}
private bool _isKill;
public void Kill ()
{
if (!this._isKill)
{
this._isKill = true;
this._actionTimer?.Kill ();
GameUpdateMgr.Instance.RemoveUpdater (OnUpdate);
// this._asyncLoader.UnloadAsync ();
}
}
}
}