UnloadUnusedAssetsOperation.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. namespace YooAsset
  5. {
  6. public sealed class UnloadUnusedAssetsOperation : AsyncOperationBase
  7. {
  8. private enum ESteps
  9. {
  10. None,
  11. UnloadUnused,
  12. Done,
  13. }
  14. private readonly ResourceManager _resManager;
  15. private readonly int _loopCount;
  16. private ESteps _steps = ESteps.None;
  17. internal UnloadUnusedAssetsOperation(ResourceManager resourceManager, int loopCount)
  18. {
  19. _resManager = resourceManager;
  20. _loopCount = loopCount;
  21. }
  22. internal override void InternalStart()
  23. {
  24. _steps = ESteps.UnloadUnused;
  25. }
  26. internal override void InternalUpdate()
  27. {
  28. if (_steps == ESteps.None || _steps == ESteps.Done)
  29. return;
  30. if (_steps == ESteps.UnloadUnused)
  31. {
  32. for (int i = 0; i < _loopCount; i++)
  33. {
  34. LoopUnloadUnused();
  35. }
  36. _steps = ESteps.Done;
  37. Status = EOperationStatus.Succeed;
  38. }
  39. }
  40. internal override void InternalWaitForAsyncComplete()
  41. {
  42. while (true)
  43. {
  44. if (ExecuteWhileDone())
  45. {
  46. _steps = ESteps.Done;
  47. break;
  48. }
  49. }
  50. }
  51. internal override string InternalGetDesc()
  52. {
  53. return $"LoopCount : {_loopCount}";
  54. }
  55. /// <summary>
  56. /// 说明:资源包之间会有深层的依赖链表,需要多次迭代才可以在单帧内卸载!
  57. /// </summary>
  58. private void LoopUnloadUnused()
  59. {
  60. var removeList = new List<LoadBundleFileOperation>(_resManager.LoaderDic.Count);
  61. // 注意:优先销毁资源提供者
  62. foreach (var loader in _resManager.LoaderDic.Values)
  63. {
  64. loader.TryDestroyProviders();
  65. }
  66. // 获取销毁列表
  67. foreach (var loader in _resManager.LoaderDic.Values)
  68. {
  69. if (loader.CanDestroyLoader())
  70. {
  71. removeList.Add(loader);
  72. }
  73. }
  74. // 销毁文件加载器
  75. foreach (var loader in removeList)
  76. {
  77. string bundleName = loader.LoadBundleInfo.Bundle.BundleName;
  78. loader.DestroyLoader();
  79. _resManager.LoaderDic.Remove(bundleName);
  80. }
  81. }
  82. }
  83. }