Created
October 20, 2016 07:02
-
-
Save birdinforest/2b4bf985c8c39282c4ebb4f9443ab7e5 to your computer and use it in GitHub Desktop.
Attach on object and handle all of trigger events depends on validation rules on layers and tags.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment