Skip to content

Instantly share code, notes, and snippets.

@brunomikoski
Created September 28, 2015 19:28
Show Gist options
  • Save brunomikoski/91b85ebd9415ab04dc22 to your computer and use it in GitHub Desktop.
Save brunomikoski/91b85ebd9415ab04dc22 to your computer and use it in GitHub Desktop.
General trigger for detecting collisions
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[RequireComponent(typeof(Collider))]
/// <summary>
/// General purpose trigger volume system
///
/// </summary>
/// <author>Bruno Mikoski</author>
public class TriggerVolume : MonoBehaviour
{
[SerializeField]
private LayerMask collisionMask = -1;
private new Collider collider;
private List<Collider> containing;
public event TriggerChangeHandler TriggerExitEvent;
public event TriggerChangeHandler TriggerEnterEvent;
public event TriggerChangeHandler TriggerStayEvent;
public int ContainCount { get { return containing.Count; } }
public delegate void TriggerChangeHandler(TriggerVolume volume, Collider collider);
private void Awake()
{
containing = new List<Collider>();
collider = GetComponent<Collider>();
collider.isTrigger = true;
}
public void SetCollisionMask(LayerMask targetLayerMask)
{
collisionMask = targetLayerMask;
}
public void ToggleVolume(bool enable)
{
if (enable)
collider.enabled = true;
else
Disable();
}
private void Disable()
{
collider.enabled = false;
if (TriggerExitEvent == null)
return;
for (int i = 0; i < containing.Count; i++)
{
Collider target = containing[i];
containing.RemoveAt(i);
i--;
TriggerExitEvent(this, target);
}
}
public Collider GetContaining(int index)
{
return containing[index];
}
public bool Contains(Collider other)
{
return containing.Contains(other);
}
public void OnTriggerEnter(Collider other)
{
if (!IsInLayerMask(other.gameObject))
return;
if (!containing.Contains(other))
{
containing.Add(other);
if (TriggerEnterEvent != null)
TriggerEnterEvent(this, other);
}
}
public void OnTriggerExit(Collider other)
{
if (!IsInLayerMask(other.gameObject))
return;
containing.Remove(other);
if (TriggerExitEvent != null)
TriggerExitEvent(this, other);
}
public void OnTriggerStay(Collider other)
{
if (!IsInLayerMask(other.gameObject))
return;
if (!containing.Contains(other))
return;
if (TriggerStayEvent != null)
TriggerStayEvent(this, other);
}
private bool IsInLayerMask(GameObject targetGameObject)
{
return ((collisionMask.value & (1 << targetGameObject.layer)) > 0);
}
#if UNITY_EDITOR
private void OnDrawGizmos()
{
if (containing != null)
{
for (int i = 0; i < containing.Count; i++)
{
if (containing[i] != null)
{
Gizmos.DrawSphere(containing[i].transform.position, 0.1f);
Gizmos.DrawLine(transform.position, containing[i].transform.position);
}
}
}
}
#endif
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment