Search Unity

OnTriggerEnter does not work propperly

Discussion in 'Physics' started by jordihuertas, Nov 8, 2018.

  1. jordihuertas

    jordihuertas

    Joined:
    Nov 8, 2018
    Posts:
    4
    I am having a trouble with OnTriggerEnter with a lot of objects.

    I have a NavMeshAgent moving randomly throught the scene, then I have a sphere collider inside a children to detect nearby objects. If the object has an allowed tag it adds to the objects_near List.

    It starts working right, but when it is working 1 or 2 minutes it starts dropping the objects_near variable to a wrong value, sometimes to 0, then, a few minutes later it drops to 0 permanently.

    Is it a Unity bug? Is it my fault because I am using a lot of resources?

    https://imgur.com/toLIMew

    Code (CSharp):
    1.         void OnTriggerEnter(Collider col)
    2.     {
    3.         string tagname = col.gameObject.tag;
    4.    
    5.         for (int i = 0; i < tags_allowed.Length; i++)
    6.         {
    7.             if (tags_allowed[i] == tagname)
    8.             {
    9.                 objects_near.Add(col.gameObject);
    10.             }
    11.         }
    12.     }
    13.  
    14.     void OnTriggerExit(Collider col)
    15.     {
    16.         string tagname = col.gameObject.tag;
    17.    
    18.         for (int i = 0; i < tags_allowed.Length; i++)
    19.         {
    20.             if (tags_allowed[i] == tagname)
    21.             {
    22.                 objects_near.Remove(col.gameObject);
    23.             }
    24.         }
    25.     }
     
    Last edited: Nov 9, 2018