# Unity - OnTriggerEnter & OnTriggerExit strange behavior

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 a few secs 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

    void OnTriggerEnter(Collider col)
{
string tagname = col.gameObject.tag;

for (int i = 0; i < tags_allowed.Length; i++)
{
if (tags_allowed[i] == tagname)
{
}
}
}

void OnTriggerExit(Collider col)
{
string tagname = col.gameObject.tag;

for (int i = 0; i < tags_allowed.Length; i++)
{
if (tags_allowed[i] == tagname)
{
objects_near.Remove(col.gameObject);
}
}
}

• I'm not entirely sure OnTriggerEnter() detects more than one object everytime it is called;
– user115399
Nov 9 '18 at 21:51
• As an aside, generally you'll want to compare tags using the CompareTag method, not ==. This saves some extra marshalling with each comparison. Nov 10 '18 at 15:25

# EDITED:

Found a solution not using triggers.

I have removed Triggers functions and changed the functionality.

First I check all the GameObjects in the scene with the allowed tags. (tags_allowed is a string array).

Then I check the distance from the IA (NavMeshAgent) to each object in the scene with an allowd tag.

If the GameObject detected is near than a distance I add it to the objects_near List. And if it is not, I remove it.

### void Update()

objects_near_tmp = null;
for (int i = 0; i < tags_allowed.Length; i ++)
{
objects_near_tmp = GameObject.FindGameObjectsWithTag(tags_allowed[i]);
for (int j = 0; j < objects_near_tmp.Length; j++)
{
float dist = Vector3.Distance(objects_near_tmp[j].transform.position, transform.position);
if (dist < 20f)
{
if (objects_near.Count > 0)
{
for (int k = 0; k < objects_near.Count; k++)
{
if (objects_near[k] == objects_near_tmp[j])
{
}
}

{
}
}
else
{