66 lines
1.8 KiB
C#
66 lines
1.8 KiB
C#
using UnityEngine;
|
|
using UnityEngine.Events;
|
|
using System.Collections;
|
|
|
|
public class CollisionEventTrigger : MonoBehaviour
|
|
{
|
|
// Public event that can be assigned in the Unity Editor
|
|
public UnityEvent OnCollisionEnterEvent;
|
|
|
|
// Delay time in seconds
|
|
public float delay = 0f;
|
|
|
|
// Tag of the object that triggers the event
|
|
public bool useTagFilter = false;
|
|
public string targetTag;
|
|
|
|
// Flag to enable triggering the event only once
|
|
public bool triggerOnlyOnce = false;
|
|
private bool hasTriggered = false;
|
|
|
|
// Method called when a collision occurs
|
|
private void OnCollisionEnter(Collision collision)
|
|
{
|
|
// Check if the event has already been triggered
|
|
if (triggerOnlyOnce && hasTriggered)
|
|
{
|
|
return;
|
|
}
|
|
|
|
//Debug.Log("Collision detected with: " + collision.gameObject.name);
|
|
|
|
if (useTagFilter && collision.gameObject.tag != targetTag)
|
|
{
|
|
//Debug.Log("Collision with object with different tag.");
|
|
return;
|
|
}
|
|
|
|
StartCoroutine(InvokeEventWithDelay());
|
|
|
|
// Set the flag to indicate the event has been triggered
|
|
if (triggerOnlyOnce)
|
|
{
|
|
hasTriggered = true;
|
|
}
|
|
}
|
|
|
|
// Coroutine to invoke the event with delay
|
|
private IEnumerator InvokeEventWithDelay()
|
|
{
|
|
// Wait for the specified delay
|
|
yield return new WaitForSeconds(delay);
|
|
|
|
// Check if the event is assigned (not null)
|
|
if (OnCollisionEnterEvent != null)
|
|
{
|
|
//Debug.Log("Event is being invoked.");
|
|
// Invoke the event
|
|
OnCollisionEnterEvent.Invoke();
|
|
}
|
|
else
|
|
{
|
|
Debug.LogWarning("OnCollisionEnterEvent is not assigned.");
|
|
}
|
|
}
|
|
}
|