using System;
using UnityEngine.Events;
namespace UnityEngine.XR.Content.Interaction
{
///
/// Calls functionality when a physics collision occurs
///
public class OnCollision : MonoBehaviour
{
[Serializable] public class CollisionEvent : UnityEvent { }
[SerializeField]
[Tooltip("If set, this collision will only fire if the other gameobject has this tag.")]
string m_RequiredTag = string.Empty;
[SerializeField]
[Tooltip("Events to fire when a matcing object collides with this one.")]
CollisionEvent m_OnEnter = new CollisionEvent();
[SerializeField]
[Tooltip("Events to fire when a matching object stops colliding with this one.")]
CollisionEvent m_OnExit = new CollisionEvent();
///
/// If set, this collision will only fire if the other gameobject has this tag.
///
public string requiredTag => m_RequiredTag;
///
/// Events to fire when a matching object collides with this one.
///
public CollisionEvent onEnter => m_OnEnter;
///
/// Events to fire when a matching object stops colliding with this one.
///
public CollisionEvent onExit => m_OnExit;
void OnCollisionEnter(Collision collision)
{
if (CanInvoke(collision.gameObject))
m_OnEnter?.Invoke(collision);
}
void OnCollisionExit(Collision collision)
{
if (CanInvoke(collision.gameObject))
m_OnExit?.Invoke(collision);
}
bool CanInvoke(GameObject otherGameObject)
{
return string.IsNullOrEmpty(m_RequiredTag) || otherGameObject.CompareTag(m_RequiredTag);
}
}
}