344a

OnCollisionEvents_UnityC#

Jul 25th, 2025
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 5.84 KB | None | 0 0
  1. using UnityEngine;
  2. using UnityEngine.Events;
  3. using System;
  4. using System.Collections;
  5. using System.Collections.Generic;
  6.  
  7. /// <summary>
  8. /// Represents a single collision event configuration with its associated actions and debug settings.
  9. /// </summary>
  10. [Serializable]
  11. public class CollisionEventEntry
  12. {
  13.     /// <summary>
  14.     /// Defines the type of collision detection to listen for.
  15.     /// </summary>
  16.     public enum CollisionType
  17.     {
  18.         /// <summary>3D physics collision enter event</summary>
  19.         OnCollisionEnter3D,
  20.         /// <summary>2D physics collision enter event</summary>
  21.         OnCollisionEnter2D,
  22.         /// <summary>3D trigger enter event</summary>
  23.         OnTriggerEnter3D,
  24.         /// <summary>2D trigger enter event</summary>
  25.         OnTriggerEnter2D
  26.     }
  27.  
  28.     /// <summary>
  29.     /// Controls the level of debug logging for this collision event.
  30.     /// </summary>
  31.     public enum DebugMode
  32.     {
  33.         /// <summary>No debug logging</summary>
  34.         None,
  35.         /// <summary>Basic collision information</summary>
  36.         Lite,
  37.         /// <summary>Detailed collision information</summary>
  38.         Verbose
  39.     }
  40.  
  41.     [Tooltip("Friendly name for this collision event")]
  42.     public string label = "Event";
  43.  
  44.     [Tooltip("Type of collision to detect")]
  45.     public CollisionType collisionType;
  46.  
  47.     [Tooltip("Only trigger for objects with this tag (leave empty to trigger for all objects)")]
  48.     public string compareTag;
  49.  
  50.     [Tooltip("Delay in seconds before triggering the delayed event")]
  51.     [Min(0f)]
  52.     public float delay = 0f;
  53.  
  54.     [Tooltip("Event triggered immediately upon collision")]
  55.     public UnityEvent onCollision;
  56.  
  57.     [Tooltip("Event triggered after the specified delay")]
  58.     public UnityEvent delayedEvent;
  59.  
  60.     [Tooltip("Level of debug information to log")]
  61.     public DebugMode debug = DebugMode.Lite;
  62.  
  63.     /// <summary>
  64.     /// Checks if the collision matches this event's criteria.
  65.     /// </summary>
  66.     /// <param name="other">The GameObject to check against</param>
  67.     /// <param name="currentType">The type of collision that occurred</param>
  68.     /// <returns>True if the collision matches the criteria</returns>
  69.     public bool Matches(GameObject other, CollisionType currentType)
  70.     {
  71.         if (other == null) return false;
  72.         if (collisionType != currentType) return false;
  73.         if (!string.IsNullOrEmpty(compareTag) && !other.CompareTag(compareTag)) return false;
  74.         return true;
  75.     }
  76.  
  77.     /// <summary>
  78.     /// Logs debug information based on the configured debug level.
  79.     /// </summary>
  80.     public void Log(string msg, DebugMode level)
  81.     {
  82.         if (debug == DebugMode.None) return;
  83.         if (debug == DebugMode.Lite && level == DebugMode.Verbose) return;
  84.  
  85.         Debug.Log($"[CollisionEvent:{label}] {msg}");
  86.     }
  87. }
  88.  
  89. /// <summary>
  90. /// Manages multiple collision events with support for both 2D and 3D physics,
  91. /// delayed events, and configurable debug logging.
  92. /// </summary>
  93. public class OnCollisionEvents : MonoBehaviour
  94. {
  95.     [Tooltip("List of collision event configurations")]
  96.     public List<CollisionEventEntry> events = new();
  97.  
  98.     private void OnValidate()
  99.     {
  100.         // Ensure each event has a unique label for debugging
  101.         var usedLabels = new HashSet<string>();
  102.         int counter = 1;
  103.         foreach (var entry in events)
  104.         {
  105.             if (string.IsNullOrEmpty(entry.label))
  106.                 entry.label = $"Event_{counter}";
  107.             else if (usedLabels.Contains(entry.label))
  108.                 entry.label = $"{entry.label}_{counter}";
  109.            
  110.             usedLabels.Add(entry.label);
  111.             counter++;
  112.         }
  113.     }
  114.  
  115.     #region 3D Events
  116.  
  117.     private void OnCollisionEnter(Collision collision)
  118.     {
  119.         if (collision != null)
  120.             HandleEvent(collision.gameObject, CollisionEventEntry.CollisionType.OnCollisionEnter3D);
  121.     }
  122.  
  123.     private void OnTriggerEnter(Collider other)
  124.     {
  125.         if (other != null)
  126.             HandleEvent(other.gameObject, CollisionEventEntry.CollisionType.OnTriggerEnter3D);
  127.     }
  128.  
  129.     #endregion
  130.  
  131.     #region 2D Events
  132.  
  133.     private void OnCollisionEnter2D(Collision2D collision)
  134.     {
  135.         if (collision != null)
  136.             HandleEvent(collision.gameObject, CollisionEventEntry.CollisionType.OnCollisionEnter2D);
  137.     }
  138.  
  139.     private void OnTriggerEnter2D(Collider2D other)
  140.     {
  141.         if (other != null)
  142.             HandleEvent(other.gameObject, CollisionEventEntry.CollisionType.OnTriggerEnter2D);
  143.     }
  144.  
  145.     #endregion
  146.  
  147.     private void HandleEvent(GameObject other, CollisionEventEntry.CollisionType type)
  148.     {
  149.         if (other == null) return;
  150.  
  151.         foreach (var entry in events)
  152.         {
  153.             if (!entry.Matches(other, type)) continue;
  154.  
  155.             entry.Log($"Triggered by {other.name} (tag: {other.tag})", CollisionEventEntry.DebugMode.Lite);
  156.            
  157.             try
  158.             {
  159.                 entry.onCollision?.Invoke();
  160.             }
  161.             catch (Exception e)
  162.             {
  163.                 Debug.LogError($"[CollisionEvent:{entry.label}] Error in onCollision event: {e}");
  164.             }
  165.  
  166.             if (entry.delay > 0f)
  167.             {
  168.                 entry.Log($"Scheduling delayedEvent in {entry.delay} seconds", CollisionEventEntry.DebugMode.Lite);
  169.                 StartCoroutine(DelayedCall(entry));
  170.             }
  171.         }
  172.     }
  173.  
  174.     private IEnumerator DelayedCall(CollisionEventEntry entry)
  175.     {
  176.         yield return new WaitForSeconds(entry.delay);
  177.        
  178.         entry.Log("Invoking delayedEvent", CollisionEventEntry.DebugMode.Lite);
  179.         try
  180.         {
  181.             entry.delayedEvent?.Invoke();
  182.         }
  183.         catch (Exception e)
  184.         {
  185.             Debug.LogError($"[CollisionEvent:{entry.label}] Error in delayedEvent: {e}");
  186.         }
  187.     }
  188. }
  189.  
Advertisement
Add Comment
Please, Sign In to add comment