2
0

ObservableDestroyTrigger.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. using System; // require keep for Windows Universal App
  2. using UnityEngine;
  3. namespace UniRx.Triggers
  4. {
  5. [DisallowMultipleComponent]
  6. public class ObservableDestroyTrigger : MonoBehaviour
  7. {
  8. bool calledDestroy = false;
  9. Subject<Unit> onDestroy;
  10. CompositeDisposable disposablesOnDestroy;
  11. [Obsolete("Internal Use.")]
  12. internal bool IsMonitoredActivate { get; set; }
  13. public bool IsActivated { get; private set; }
  14. /// <summary>
  15. /// Check called OnDestroy.
  16. /// This property does not guarantees GameObject was destroyed,
  17. /// when gameObject is deactive, does not raise OnDestroy.
  18. /// </summary>
  19. public bool IsCalledOnDestroy { get { return calledDestroy; } }
  20. void Awake()
  21. {
  22. IsActivated = true;
  23. }
  24. /// <summary>This function is called when the MonoBehaviour will be destroyed.</summary>
  25. void OnDestroy()
  26. {
  27. if (!calledDestroy)
  28. {
  29. calledDestroy = true;
  30. if (disposablesOnDestroy != null) disposablesOnDestroy.Dispose();
  31. if (onDestroy != null) { onDestroy.OnNext(Unit.Default); onDestroy.OnCompleted(); }
  32. }
  33. }
  34. /// <summary>This function is called when the MonoBehaviour will be destroyed.</summary>
  35. public IObservable<Unit> OnDestroyAsObservable()
  36. {
  37. if (this == null) return Observable.Return(Unit.Default);
  38. if (calledDestroy) return Observable.Return(Unit.Default);
  39. return onDestroy ?? (onDestroy = new Subject<Unit>());
  40. }
  41. /// <summary>Invoke OnDestroy, this method is used on internal.</summary>
  42. public void ForceRaiseOnDestroy()
  43. {
  44. OnDestroy();
  45. }
  46. public void AddDisposableOnDestroy(IDisposable disposable)
  47. {
  48. if (calledDestroy)
  49. {
  50. disposable.Dispose();
  51. return;
  52. }
  53. if (disposablesOnDestroy == null) disposablesOnDestroy = new CompositeDisposable();
  54. disposablesOnDestroy.Add(disposable);
  55. }
  56. }
  57. }