UnloadSceneOperation.cs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using UnityEngine;
  2. using UnityEngine.SceneManagement;
  3. namespace YooAsset
  4. {
  5. /// <summary>
  6. /// 场景卸载异步操作类
  7. /// </summary>
  8. public sealed class UnloadSceneOperation : AsyncOperationBase
  9. {
  10. private enum EFlag
  11. {
  12. Normal,
  13. Error,
  14. }
  15. private enum ESteps
  16. {
  17. None,
  18. UnLoad,
  19. Checking,
  20. Done,
  21. }
  22. private readonly EFlag _flag;
  23. private ESteps _steps = ESteps.None;
  24. private Scene _scene;
  25. private AsyncOperation _asyncOp;
  26. internal UnloadSceneOperation(string error)
  27. {
  28. _flag = EFlag.Error;
  29. Error = error;
  30. }
  31. internal UnloadSceneOperation(Scene scene)
  32. {
  33. _flag = EFlag.Normal;
  34. _scene = scene;
  35. }
  36. internal override void Start()
  37. {
  38. if (_flag == EFlag.Normal)
  39. {
  40. _steps = ESteps.UnLoad;
  41. }
  42. else if (_flag == EFlag.Error)
  43. {
  44. _steps = ESteps.Done;
  45. Status = EOperationStatus.Failed;
  46. }
  47. else
  48. {
  49. throw new System.NotImplementedException(_flag.ToString());
  50. }
  51. }
  52. internal override void Update()
  53. {
  54. if (_steps == ESteps.None || _steps == ESteps.Done)
  55. return;
  56. if (_steps == ESteps.UnLoad)
  57. {
  58. if (_scene.IsValid() && _scene.isLoaded)
  59. {
  60. _asyncOp = SceneManager.UnloadSceneAsync(_scene);
  61. _steps = ESteps.Checking;
  62. }
  63. else
  64. {
  65. Error = "Scene is invalid or is not loaded.";
  66. _steps = ESteps.Done;
  67. Status = EOperationStatus.Failed;
  68. }
  69. }
  70. if (_steps == ESteps.Checking)
  71. {
  72. Progress = _asyncOp.progress;
  73. if (_asyncOp.isDone == false)
  74. return;
  75. _steps = ESteps.Done;
  76. Status = EOperationStatus.Succeed;
  77. }
  78. }
  79. }
  80. }