com.alicizax.unity.tuyoogam.../Runtime/ResourceManager/Operation/UnloadUnusedAssetsOperation.cs

104 lines
2.9 KiB
C#
Raw Normal View History

2025-01-09 11:31:04 +08:00
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace YooAsset
{
public sealed class UnloadUnusedAssetsOperation : AsyncOperationBase
{
private enum ESteps
{
None,
UnloadUnused,
Done,
}
private readonly ResourceManager _resManager;
2025-02-28 16:11:01 +08:00
private readonly int _loopCount;
2025-04-01 21:12:28 +08:00
private int _loopCounter = 0;
2025-01-09 11:31:04 +08:00
private ESteps _steps = ESteps.None;
2025-02-28 16:11:01 +08:00
internal UnloadUnusedAssetsOperation(ResourceManager resourceManager, int loopCount)
2025-01-09 11:31:04 +08:00
{
_resManager = resourceManager;
2025-02-28 16:11:01 +08:00
_loopCount = loopCount;
2025-01-09 11:31:04 +08:00
}
2025-02-28 16:11:01 +08:00
internal override void InternalStart()
2025-01-09 11:31:04 +08:00
{
_steps = ESteps.UnloadUnused;
2025-04-01 21:12:28 +08:00
_loopCounter = _loopCount;
2025-01-09 11:31:04 +08:00
}
2025-02-28 16:11:01 +08:00
internal override void InternalUpdate()
2025-01-09 11:31:04 +08:00
{
if (_steps == ESteps.None || _steps == ESteps.Done)
return;
if (_steps == ESteps.UnloadUnused)
{
2025-04-01 21:12:28 +08:00
while (_loopCounter > 0)
2025-01-09 11:31:04 +08:00
{
2025-04-01 21:12:28 +08:00
_loopCounter--;
2025-02-28 16:11:01 +08:00
LoopUnloadUnused();
2025-04-01 21:12:28 +08:00
if (IsWaitForAsyncComplete == false)
{
if (OperationSystem.IsBusy)
break;
}
2025-01-09 11:31:04 +08:00
}
2025-04-01 21:12:28 +08:00
if (_loopCounter <= 0)
{
_steps = ESteps.Done;
Status = EOperationStatus.Succeed;
}
2025-01-09 11:31:04 +08:00
}
}
internal override void InternalWaitForAsyncComplete()
{
while (true)
{
if (ExecuteWhileDone())
{
_steps = ESteps.Done;
break;
}
}
}
2025-04-01 21:12:28 +08:00
internal override string InternalGetDesc()
{
return $"LoopCount : {_loopCount}";
}
2025-02-28 16:11:01 +08:00
/// <summary>
/// 说明:资源包之间会有深层的依赖链表,需要多次迭代才可以在单帧内卸载!
/// </summary>
private void LoopUnloadUnused()
{
var removeList = new List<LoadBundleFileOperation>(_resManager.LoaderDic.Count);
// 注意:优先销毁资源提供者
foreach (var loader in _resManager.LoaderDic.Values)
{
loader.TryDestroyProviders();
}
// 获取销毁列表
foreach (var loader in _resManager.LoaderDic.Values)
{
if (loader.CanDestroyLoader())
{
removeList.Add(loader);
}
}
// 销毁文件加载器
foreach (var loader in removeList)
{
string bundleName = loader.LoadBundleInfo.Bundle.BundleName;
loader.DestroyLoader();
_resManager.LoaderDic.Remove(bundleName);
}
}
2025-01-09 11:31:04 +08:00
}
}