Advertisement
Guest User

Untitled

a guest
Oct 20th, 2016
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.74 KB | None | 0 0
  1. using UnityEngine;
  2. using UnityEngine.Events;
  3. using System.Collections;
  4.  
  5. /// <summary>
  6. /// Attach on trigger and set validate rule. Invoke events if validation is successful.
  7. /// </summary>
  8. public class TriggerHanlder : MonoBehaviour {
  9. public enum ValidateRule {
  10. ANY, BOTH
  11. }
  12.  
  13. [SerializeField] protected LayerMask triggerLayers;
  14. [SerializeField] protected string[] triggerTags;
  15. [SerializeField] protected ValidateRule validate;
  16.  
  17. [SerializeField] protected UnityEvent onTriggerEnter;
  18. [SerializeField] protected UnityEvent onTriggerStay;
  19. [SerializeField] protected UnityEvent onTriggerExit;
  20.  
  21. private Collider2D col2D;
  22.  
  23. protected virtual bool Validate(Collider2D other) {
  24. bool layerValid = false;
  25. bool tagValid = false;
  26.  
  27. // Always return true if layermask and tags are unassigned.
  28. if (triggerLayers.value == 0 && (triggerTags == null || triggerTags.Length == 0))
  29. return true;
  30.  
  31. bool isAny = validate == ValidateRule.ANY || triggerLayers.value == 0 || triggerTags == null || triggerTags.Length == 0;
  32.  
  33. LayerMask mask = 1 << other.gameObject.layer;
  34. if ((triggerLayers & mask) == mask) {
  35. layerValid = true;
  36. if (isAny)
  37. return true;
  38. }
  39.  
  40. for (int i = 0; i < triggerTags.Length; i++) {
  41. if (other.CompareTag(triggerTags[i])) {
  42. tagValid = true;
  43. if (isAny)
  44. return true;
  45. }
  46. }
  47.  
  48. return layerValid && tagValid;
  49. }
  50.  
  51. protected virtual void OnTriggerEnter2D(Collider2D other) {
  52. if (Validate(other) && onTriggerEnter != null) {
  53. onTriggerEnter.Invoke();
  54. }
  55. }
  56.  
  57. protected virtual void OnTriggerStay2D(Collider2D other) {
  58. if (Validate(other) && onTriggerStay != null)
  59. onTriggerStay.Invoke();
  60. }
  61.  
  62. protected virtual void OnTriggerExit2D(Collider2D other) {
  63. if (Validate(other) && onTriggerExit != null)
  64. onTriggerExit.Invoke();
  65. }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement