ObservableTriggerTrigger.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. using System; // require keep for Windows Universal App
  2. using UnityEngine;
  3. namespace UniRx.Triggers
  4. {
  5. [DisallowMultipleComponent]
  6. public class ObservableTriggerTrigger : ObservableTriggerBase
  7. {
  8. Subject<Collider> onTriggerEnter;
  9. /// <summary>OnTriggerEnter is called when the Collider other enters the trigger.</summary>
  10. void OnTriggerEnter(Collider other)
  11. {
  12. if (onTriggerEnter != null) onTriggerEnter.OnNext(other);
  13. }
  14. /// <summary>OnTriggerEnter is called when the Collider other enters the trigger.</summary>
  15. public IObservable<Collider> OnTriggerEnterAsObservable()
  16. {
  17. return onTriggerEnter ?? (onTriggerEnter = new Subject<Collider>());
  18. }
  19. Subject<Collider> onTriggerExit;
  20. /// <summary>OnTriggerExit is called when the Collider other has stopped touching the trigger.</summary>
  21. void OnTriggerExit(Collider other)
  22. {
  23. if (onTriggerExit != null) onTriggerExit.OnNext(other);
  24. }
  25. /// <summary>OnTriggerExit is called when the Collider other has stopped touching the trigger.</summary>
  26. public IObservable<Collider> OnTriggerExitAsObservable()
  27. {
  28. return onTriggerExit ?? (onTriggerExit = new Subject<Collider>());
  29. }
  30. Subject<Collider> onTriggerStay;
  31. /// <summary>OnTriggerStay is called once per frame for every Collider other that is touching the trigger.</summary>
  32. void OnTriggerStay(Collider other)
  33. {
  34. if (onTriggerStay != null) onTriggerStay.OnNext(other);
  35. }
  36. /// <summary>OnTriggerStay is called once per frame for every Collider other that is touching the trigger.</summary>
  37. public IObservable<Collider> OnTriggerStayAsObservable()
  38. {
  39. return onTriggerStay ?? (onTriggerStay = new Subject<Collider>());
  40. }
  41. protected override void RaiseOnCompletedOnDestroy()
  42. {
  43. if (onTriggerEnter != null)
  44. {
  45. onTriggerEnter.OnCompleted();
  46. }
  47. if (onTriggerExit != null)
  48. {
  49. onTriggerExit.OnCompleted();
  50. }
  51. if (onTriggerStay != null)
  52. {
  53. onTriggerStay.OnCompleted();
  54. }
  55. }
  56. }
  57. }