SceneAsyncOperation.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. using System;
  2. using UnityEngine;
  3. using UnityEngine.SceneManagement;
  4. using KFADA = XGame.Framework.Asyncs;
  5. namespace XGame.Framework.Asset
  6. {
  7. public class SceneAsyncOperation<T> : KFADA.ResultAsync<T>
  8. {
  9. public object SceneAsset;
  10. private string _sceneName;
  11. private IAssetModule _assetModule;
  12. private AsyncOperation _async;
  13. private KFADA.IAsync _abAsync;
  14. private float _abProgress = 0.5f;
  15. public override float Progress
  16. {
  17. get
  18. {
  19. if (_abAsync != null || _async != null) return _abProgress;
  20. else
  21. {
  22. if (!IsCompleted)
  23. return _abProgress + _async.progress / 2;
  24. else
  25. return 1.0f;
  26. }
  27. }
  28. }
  29. public SceneAsyncOperation(string sceneName, IAssetModule assetModule)
  30. {
  31. _sceneName = sceneName;
  32. _assetModule = assetModule;
  33. Init();
  34. }
  35. private void Init()
  36. {
  37. _abAsync = _assetModule.LoadSceneBundleAsync(_sceneName);
  38. _abAsync.On((async) =>
  39. {
  40. if (async.IsCompleted)
  41. {
  42. _async = SceneManager.LoadSceneAsync(_sceneName, LoadSceneMode.Additive);
  43. _async.completed += (a) =>
  44. {
  45. bool isFind = false;
  46. var objects = SceneManager.GetSceneByName(_sceneName).GetRootGameObjects();
  47. foreach (var item in objects)
  48. {
  49. var result = item.GetComponent<T>();
  50. if (result != null)
  51. {
  52. Result = result;
  53. isFind = true;
  54. break;
  55. }
  56. }
  57. if (!isFind) throw new NullReferenceException($"未发现该对象:{typeof(T)},请检查场景资源文件:{_sceneName}");
  58. Completed();
  59. };
  60. }
  61. });
  62. }
  63. }
  64. }