ObservableTriggerBase.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using System; // require keep for Windows Universal App
  2. using UnityEngine;
  3. namespace UniRx.Triggers
  4. {
  5. public abstract class ObservableTriggerBase : MonoBehaviour
  6. {
  7. bool calledAwake = false;
  8. Subject<Unit> awake;
  9. /// <summary>Awake is called when the script instance is being loaded.</summary>
  10. void Awake()
  11. {
  12. calledAwake = true;
  13. if (awake != null) { awake.OnNext(Unit.Default); awake.OnCompleted(); }
  14. }
  15. /// <summary>Awake is called when the script instance is being loaded.</summary>
  16. public IObservable<Unit> AwakeAsObservable()
  17. {
  18. if (calledAwake) return Observable.Return(Unit.Default);
  19. return awake ?? (awake = new Subject<Unit>());
  20. }
  21. bool calledStart = false;
  22. Subject<Unit> start;
  23. /// <summary>Start is called on the frame when a script is enabled just before any of the Update methods is called the first time.</summary>
  24. void Start()
  25. {
  26. calledStart = true;
  27. if (start != null) { start.OnNext(Unit.Default); start.OnCompleted(); }
  28. }
  29. /// <summary>Start is called on the frame when a script is enabled just before any of the Update methods is called the first time.</summary>
  30. public IObservable<Unit> StartAsObservable()
  31. {
  32. if (calledStart) return Observable.Return(Unit.Default);
  33. return start ?? (start = new Subject<Unit>());
  34. }
  35. bool calledDestroy = false;
  36. Subject<Unit> onDestroy;
  37. /// <summary>This function is called when the MonoBehaviour will be destroyed.</summary>
  38. void OnDestroy()
  39. {
  40. calledDestroy = true;
  41. if (onDestroy != null) { onDestroy.OnNext(Unit.Default); onDestroy.OnCompleted(); }
  42. RaiseOnCompletedOnDestroy();
  43. }
  44. /// <summary>This function is called when the MonoBehaviour will be destroyed.</summary>
  45. public IObservable<Unit> OnDestroyAsObservable()
  46. {
  47. if (this == null) return Observable.Return(Unit.Default);
  48. if (calledDestroy) return Observable.Return(Unit.Default);
  49. return onDestroy ?? (onDestroy = new Subject<Unit>());
  50. }
  51. protected abstract void RaiseOnCompletedOnDestroy();
  52. }
  53. }