1
0

ObservableCollisionTrigger.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 ObservableCollisionTrigger : ObservableTriggerBase
  7. {
  8. Subject<Collision> onCollisionEnter;
  9. /// <summary>OnCollisionEnter is called when this collider/rigidbody has begun touching another rigidbody/collider.</summary>
  10. void OnCollisionEnter(Collision collision)
  11. {
  12. if (onCollisionEnter != null) onCollisionEnter.OnNext(collision);
  13. }
  14. /// <summary>OnCollisionEnter is called when this collider/rigidbody has begun touching another rigidbody/collider.</summary>
  15. public IObservable<Collision> OnCollisionEnterAsObservable()
  16. {
  17. return onCollisionEnter ?? (onCollisionEnter = new Subject<Collision>());
  18. }
  19. Subject<Collision> onCollisionExit;
  20. /// <summary>OnCollisionExit is called when this collider/rigidbody has stopped touching another rigidbody/collider.</summary>
  21. void OnCollisionExit(Collision collisionInfo)
  22. {
  23. if (onCollisionExit != null) onCollisionExit.OnNext(collisionInfo);
  24. }
  25. /// <summary>OnCollisionExit is called when this collider/rigidbody has stopped touching another rigidbody/collider.</summary>
  26. public IObservable<Collision> OnCollisionExitAsObservable()
  27. {
  28. return onCollisionExit ?? (onCollisionExit = new Subject<Collision>());
  29. }
  30. Subject<Collision> onCollisionStay;
  31. /// <summary>OnCollisionStay is called once per frame for every collider/rigidbody that is touching rigidbody/collider.</summary>
  32. void OnCollisionStay(Collision collisionInfo)
  33. {
  34. if (onCollisionStay != null) onCollisionStay.OnNext(collisionInfo);
  35. }
  36. /// <summary>OnCollisionStay is called once per frame for every collider/rigidbody that is touching rigidbody/collider.</summary>
  37. public IObservable<Collision> OnCollisionStayAsObservable()
  38. {
  39. return onCollisionStay ?? (onCollisionStay = new Subject<Collision>());
  40. }
  41. protected override void RaiseOnCompletedOnDestroy()
  42. {
  43. if (onCollisionEnter != null)
  44. {
  45. onCollisionEnter.OnCompleted();
  46. }
  47. if (onCollisionExit != null)
  48. {
  49. onCollisionExit.OnCompleted();
  50. }
  51. if (onCollisionStay != null)
  52. {
  53. onCollisionStay.OnCompleted();
  54. }
  55. }
  56. }
  57. }