ObservableCollision2DTrigger.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 ObservableCollision2DTrigger : ObservableTriggerBase
  7. {
  8. Subject<Collision2D> onCollisionEnter2D;
  9. /// <summary>Sent when an incoming collider makes contact with this object's collider (2D physics only).</summary>
  10. void OnCollisionEnter2D(Collision2D coll)
  11. {
  12. if (onCollisionEnter2D != null) onCollisionEnter2D.OnNext(coll);
  13. }
  14. /// <summary>Sent when an incoming collider makes contact with this object's collider (2D physics only).</summary>
  15. public IObservable<Collision2D> OnCollisionEnter2DAsObservable()
  16. {
  17. return onCollisionEnter2D ?? (onCollisionEnter2D = new Subject<Collision2D>());
  18. }
  19. Subject<Collision2D> onCollisionExit2D;
  20. /// <summary>Sent when a collider on another object stops touching this object's collider (2D physics only).</summary>
  21. void OnCollisionExit2D(Collision2D coll)
  22. {
  23. if (onCollisionExit2D != null) onCollisionExit2D.OnNext(coll);
  24. }
  25. /// <summary>Sent when a collider on another object stops touching this object's collider (2D physics only).</summary>
  26. public IObservable<Collision2D> OnCollisionExit2DAsObservable()
  27. {
  28. return onCollisionExit2D ?? (onCollisionExit2D = new Subject<Collision2D>());
  29. }
  30. Subject<Collision2D> onCollisionStay2D;
  31. /// <summary>Sent each frame where a collider on another object is touching this object's collider (2D physics only).</summary>
  32. void OnCollisionStay2D(Collision2D coll)
  33. {
  34. if (onCollisionStay2D != null) onCollisionStay2D.OnNext(coll);
  35. }
  36. /// <summary>Sent each frame where a collider on another object is touching this object's collider (2D physics only).</summary>
  37. public IObservable<Collision2D> OnCollisionStay2DAsObservable()
  38. {
  39. return onCollisionStay2D ?? (onCollisionStay2D = new Subject<Collision2D>());
  40. }
  41. protected override void RaiseOnCompletedOnDestroy()
  42. {
  43. if (onCollisionEnter2D != null)
  44. {
  45. onCollisionEnter2D.OnCompleted();
  46. }
  47. if (onCollisionExit2D != null)
  48. {
  49. onCollisionExit2D.OnCompleted();
  50. }
  51. if (onCollisionStay2D != null)
  52. {
  53. onCollisionStay2D.OnCompleted();
  54. }
  55. }
  56. }
  57. }