Last active
August 17, 2016 14:37
-
-
Save edwardrowe/f280a1a7f08b6a204745 to your computer and use it in GitHub Desktop.
Unity Trigger Action - used to wire up actions to trigger events
This file contains 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
// Script by Edward Rowe (@edwardlrowe) | |
using UnityEngine; | |
#if UNITY_EDITOR | |
using UnityEditor; | |
#endif | |
[RequireComponent (typeof(Collider2D))] | |
public class TriggerAction : MonoBehaviour | |
{ | |
[Tooltip ("Tag strings of valid objects to activate Trigger.")] | |
public string[] FilterTags; | |
[Tooltip ("Disable the collider and Trigger when Touched.")] | |
public bool DisableOnTouch; | |
public UnityEngine.Events.UnityEvent | |
TouchEvent; | |
Collider2D myCollider { | |
get { | |
if (_myCollider == null) { | |
_myCollider = GetComponent<Collider2D> (); | |
} | |
return _myCollider; | |
} | |
} | |
Collider2D _myCollider; | |
void OnTriggerEnter2D (Collider2D other) | |
{ | |
if (ShouldColliderFireAction (other)) { | |
FireTouchEvent (); | |
} | |
} | |
bool ShouldColliderFireAction (Collider2D activator) | |
{ | |
if (FilterTags == null || FilterTags.Length == 0) { | |
return true; | |
} | |
// Search for matching tags | |
for (int i = 0; i < FilterTags.Length; i++) { | |
if (activator.CompareTag (FilterTags[i])) { | |
return true; | |
} | |
} | |
// Matched no tags | |
return false; | |
} | |
void FireTouchEvent () | |
{ | |
TouchEvent.Invoke (); | |
if (DisableOnTouch) { | |
myCollider.enabled = false; | |
enabled = false; | |
} | |
} | |
} | |
#if UNITY_EDITOR | |
[CustomEditor (typeof (TriggerAction)), CanEditMultipleObjects] | |
public class TriggerActionInspector : UnityEditor.Editor | |
{ | |
public override void OnInspectorGUI () | |
{ | |
DrawDefaultInspector (); | |
var triggerAction = target as TriggerAction; | |
Collider2D collider = triggerAction.GetComponent<Collider2D> (); | |
if (collider == null) { | |
EditorGUILayout.HelpBox ("Missing Collider2D on TriggerAction", MessageType.Error); | |
} else { | |
if (!collider.isTrigger) { | |
EditorGUILayout.HelpBox ("Trigger Events will not be called unless collider is a Trigger", MessageType.Warning); | |
} | |
} | |
} | |
} | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment