SRDependencyServiceBase.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. //#define ENABLE_LOGGING
  2. namespace SRF.Service
  3. {
  4. using System;
  5. using System.Collections;
  6. using System.Diagnostics;
  7. using UnityEngine;
  8. using Debug = UnityEngine.Debug;
  9. using Object = UnityEngine.Object;
  10. /// <summary>
  11. /// A service which has async-loading dependencies
  12. /// </summary>
  13. /// <typeparam name="T"></typeparam>
  14. public abstract class SRDependencyServiceBase<T> : SRServiceBase<T>, IAsyncService where T : class
  15. {
  16. private bool _isLoaded;
  17. protected abstract Type[] Dependencies { get; }
  18. public bool IsLoaded
  19. {
  20. get { return _isLoaded; }
  21. }
  22. [Conditional("ENABLE_LOGGING")]
  23. private void Log(string msg, Object target)
  24. {
  25. //#if ENABLE_LOGGING
  26. Debug.Log(msg, target);
  27. //#endif
  28. }
  29. protected override void Start()
  30. {
  31. base.Start();
  32. StartCoroutine(LoadDependencies());
  33. }
  34. /// <summary>
  35. /// Invoked once all dependencies are loaded
  36. /// </summary>
  37. protected virtual void OnLoaded() {}
  38. private IEnumerator LoadDependencies()
  39. {
  40. SRServiceManager.LoadingCount++;
  41. Log("[Service] Loading service ({0})".Fmt(GetType().Name), this);
  42. foreach (var d in Dependencies)
  43. {
  44. var hasService = SRServiceManager.HasService(d);
  45. Log("[Service] Resolving Service ({0}) HasService: {1}".Fmt(d.Name, hasService), this);
  46. if (hasService)
  47. {
  48. continue;
  49. }
  50. var service = SRServiceManager.GetService(d);
  51. if (service == null)
  52. {
  53. Debug.LogError("[Service] Could not resolve dependency ({0})".Fmt(d.Name));
  54. enabled = false;
  55. yield break;
  56. }
  57. var a = service as IAsyncService;
  58. if (a != null)
  59. {
  60. while (!a.IsLoaded)
  61. {
  62. yield return new WaitForEndOfFrame();
  63. }
  64. }
  65. }
  66. Log("[Service] Loading service ({0}) complete.".Fmt(GetType().Name), this);
  67. _isLoaded = true;
  68. SRServiceManager.LoadingCount--;
  69. OnLoaded();
  70. }
  71. }
  72. }