Search Unity

Object Destroyed while inside Trigger not causing exit signal

Discussion in 'Editor & General Support' started by richardzzzarnold, Jun 21, 2020.

  1. richardzzzarnold

    richardzzzarnold

    Joined:
    Aug 2, 2012
    Posts:
    142
    I have found that I have a case in which my trigger is not realising that it no longer has an occupant collider. I have an OnTriggerStay and OnTriggerExit function, however , in the case when an object is being destroyed while inside the trigger box, it is not registering as an exit. How exactly would I go about checking to see if it exists or not?
     
  2. CoolCosmos

    CoolCosmos

    Joined:
    Nov 21, 2016
    Posts:
    247
    Hi @richardzzzarnold,

    You can create a temporary collider around the object and then check for the objects that you search... Then you can run any function you like. You can use it as a bool. If there's no object that you search for, then you can do something...

    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class MyScript : MonoBehaviour
    4. {
    5.     public float radius;
    6.  
    7.     private void MyCode()
    8.     {
    9.         Collider[] colliders = Physics.OverlapSphere(transform.position, radius);
    10.  
    11.         foreach (Collider col in colliders)
    12.         {
    13.             if (col.gameObject.tag == "Enemy") //search for tag...
    14.             {
    15.                 Destroy(col.gameObject);
    16.             }
    17.  
    18.             if (col.gameObject.layer == LayerMask.NameToLayer("Enemy")) //search for layer...
    19.             {
    20.                 Destroy(col.gameObject);
    21.             }
    22.         }
    23.     }
    24. }
    25.  
     
  3. CoolCosmos

    CoolCosmos

    Joined:
    Nov 21, 2016
    Posts:
    247
    If there are not any objects with Enemy layer then do something...
    Code (CSharp):
    1. if (!Physics.OverlapSphere(transform.position, radius, LayerMask.GetMask("Enemy")))
    2.     {
    3.       //Do Something...
    4.     }