Skip to content

Instantly share code, notes, and snippets.

@marinbenc
Last active May 10, 2018 08:54
Show Gist options
  • Select an option

  • Save marinbenc/a96325225df464a95899a55d23e48377 to your computer and use it in GitHub Desktop.

Select an option

Save marinbenc/a96325225df464a95899a55d23e48377 to your computer and use it in GitHub Desktop.
Collision Handler - A Unity component to add callbacks to respond to collisions or triggers
// Often I need to add multiple triggers to single object that do different things.
// This script lets you add a child containing a collider, and assign Events to
// happen when the collider is entered or triggered.
//
// Simply create a child object, add a collider and add this script. Set up events
// like you would for any other components. (like Button etc.)
using System;
using UnityEngine;
using UnityEngine.Events;
[Serializable]
public class CollisionEvent : UnityEvent<Collision2D> {}
[Serializable]
public class TriggerEvent : UnityEvent<Collider2D> {}
[RequireComponent(typeof(Collider2D))]
public class CollisionHandler : MonoBehaviour
{
public TriggerEvent OnTriggerEnter;
public CollisionEvent OnCollisionEnter;
private void OnCollisionEnter2D(Collision2D other)
{
if (OnCollisionEnter != null)
{
OnCollisionEnter.Invoke(other);
}
}
private void OnTriggerEnter2D(Collider2D other)
{
if (OnTriggerEnter != null)
{
OnTriggerEnter.Invoke(other);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment