Last active
June 7, 2020 12:32
-
-
Save nonathaj/6daaffd80e3a54a6c052 to your computer and use it in GitHub Desktop.
Trigger activator/handler for Unity3D
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
using UnityEngine; | |
using UnityEngine.Events; | |
using System; | |
using System.Collections; | |
using System.Collections.Generic; | |
/// <summary> | |
/// Trigger3D class | |
/// | |
/// A trigger is considered ACTIVE when there is at least one object inside of it. | |
/// | |
/// Contains a list of objects inside the trigger, and if the trigger is active or not. | |
/// The user is responsible for setting up proper layering for collisions with this object. | |
/// </summary> | |
[AddComponentMenu("Event/Event Trigger3D")] | |
[RequireComponent( typeof(Collider) )] | |
public class Trigger3D : MonoBehaviour | |
{ | |
///This trigger is considered active when another object is inside of it. It is inactive if no objects are inside of it | |
public bool Active { get { return inside.Count > 0; } } | |
private Collider col3D; | |
/// The 3D Collider for this trigger. | |
public Collider ColliderComponent { get { return col3D ?? (col3D = GetComponent<Collider>()); } } | |
///all the objects inside this trigger | |
List<Collider> inside = new List<Collider>(); | |
///A list of all the 3d colliders currently inside the 3d trigger | |
public IEnumerable<Collider> Inside { get { return inside; } } | |
[SerializeField, Tooltip("called when this trigger is activated by a 3d collider")] | |
UnityEvent onActivate; | |
public UnityEvent OnActivate { get { return onActivate; } } | |
[SerializeField, Tooltip("called when this trigger is deactivated by a 3d collider")] | |
UnityEvent onDeactivate; | |
public UnityEvent OnDeactivate { get { return onDeactivate; } } | |
[Serializable] | |
public class ColliderEvent : UnityEvent<Collider> { } | |
[SerializeField, Tooltip("called when a 3d collider enters this trigger")] | |
ColliderEvent onEnter; | |
public ColliderEvent OnEnter { get { return onEnter; } } | |
[SerializeField, Tooltip("called when a 3d collider exists this trigger")] | |
private ColliderEvent onExit; | |
public ColliderEvent OnExit { get { return onExit; } } | |
void Awake() | |
{ | |
ColliderComponent.isTrigger = true; | |
} | |
void OnTriggerEnter(Collider other) | |
{ | |
bool wasActive = Active; | |
inside.Add(other); | |
OnEnter.Invoke(other); | |
if (!wasActive) | |
OnActivate.Invoke(); | |
} | |
void OnTriggerExit(Collider other) | |
{ | |
bool wasActive = Active; | |
inside.Remove(other); | |
OnExit.Invoke(other); | |
if (wasActive && !Active) | |
OnDeactivate.Invoke(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment