Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using UnityEngine.Events;
- using System.Collections;
- /// <summary>
- /// Attach on trigger and set validate rule. Invoke events if validation is successful.
- /// </summary>
- public class TriggerHanlder : MonoBehaviour {
- public enum ValidateRule {
- ANY, BOTH
- }
- [SerializeField] protected LayerMask triggerLayers;
- [SerializeField] protected string[] triggerTags;
- [SerializeField] protected ValidateRule validate;
- [SerializeField] protected UnityEvent onTriggerEnter;
- [SerializeField] protected UnityEvent onTriggerStay;
- [SerializeField] protected UnityEvent onTriggerExit;
- private Collider2D col2D;
- protected virtual bool Validate(Collider2D other) {
- bool layerValid = false;
- bool tagValid = false;
- // Always return true if layermask and tags are unassigned.
- if (triggerLayers.value == 0 && (triggerTags == null || triggerTags.Length == 0))
- return true;
- bool isAny = validate == ValidateRule.ANY || triggerLayers.value == 0 || triggerTags == null || triggerTags.Length == 0;
- LayerMask mask = 1 << other.gameObject.layer;
- if ((triggerLayers & mask) == mask) {
- layerValid = true;
- if (isAny)
- return true;
- }
- for (int i = 0; i < triggerTags.Length; i++) {
- if (other.CompareTag(triggerTags[i])) {
- tagValid = true;
- if (isAny)
- return true;
- }
- }
- return layerValid && tagValid;
- }
- protected virtual void OnTriggerEnter2D(Collider2D other) {
- if (Validate(other) && onTriggerEnter != null) {
- onTriggerEnter.Invoke();
- }
- }
- protected virtual void OnTriggerStay2D(Collider2D other) {
- if (Validate(other) && onTriggerStay != null)
- onTriggerStay.Invoke();
- }
- protected virtual void OnTriggerExit2D(Collider2D other) {
- if (Validate(other) && onTriggerExit != null)
- onTriggerExit.Invoke();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement