ObservableTrigger2DTrigger.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. using System; // require keep for Windows Universal App
  2. using UnityEngine;
  3. namespace UniRx.Triggers
  4. {
  5. [DisallowMultipleComponent]
  6. public class ObservableTrigger2DTrigger : ObservableTriggerBase
  7. {
  8. Subject<Collider2D> onTriggerEnter2D;
  9. /// <summary>Sent when another object enters a trigger collider attached to this object (2D physics only).</summary>
  10. void OnTriggerEnter2D(Collider2D other)
  11. {
  12. if (onTriggerEnter2D != null) onTriggerEnter2D.OnNext(other);
  13. }
  14. /// <summary>Sent when another object enters a trigger collider attached to this object (2D physics only).</summary>
  15. public IObservable<Collider2D> OnTriggerEnter2DAsObservable()
  16. {
  17. return onTriggerEnter2D ?? (onTriggerEnter2D = new Subject<Collider2D>());
  18. }
  19. Subject<Collider2D> onTriggerExit2D;
  20. /// <summary>Sent when another object leaves a trigger collider attached to this object (2D physics only).</summary>
  21. void OnTriggerExit2D(Collider2D other)
  22. {
  23. if (onTriggerExit2D != null) onTriggerExit2D.OnNext(other);
  24. }
  25. /// <summary>Sent when another object leaves a trigger collider attached to this object (2D physics only).</summary>
  26. public IObservable<Collider2D> OnTriggerExit2DAsObservable()
  27. {
  28. return onTriggerExit2D ?? (onTriggerExit2D = new Subject<Collider2D>());
  29. }
  30. Subject<Collider2D> onTriggerStay2D;
  31. /// <summary>Sent each frame where another object is within a trigger collider attached to this object (2D physics only).</summary>
  32. void OnTriggerStay2D(Collider2D other)
  33. {
  34. if (onTriggerStay2D != null) onTriggerStay2D.OnNext(other);
  35. }
  36. /// <summary>Sent each frame where another object is within a trigger collider attached to this object (2D physics only).</summary>
  37. public IObservable<Collider2D> OnTriggerStay2DAsObservable()
  38. {
  39. return onTriggerStay2D ?? (onTriggerStay2D = new Subject<Collider2D>());
  40. }
  41. protected override void RaiseOnCompletedOnDestroy()
  42. {
  43. if (onTriggerEnter2D != null)
  44. {
  45. onTriggerEnter2D.OnCompleted();
  46. }
  47. if (onTriggerExit2D != null)
  48. {
  49. onTriggerExit2D.OnCompleted();
  50. }
  51. if (onTriggerStay2D != null)
  52. {
  53. onTriggerStay2D.OnCompleted();
  54. }
  55. }
  56. }
  57. }