foreach (GameObject police in PoliceObjects )
{
//Check for distance and then act
}
foreach( Same Goes for other 5 arrays of tagged objects)
Every active object is saved to HashSet Collection. But I think FindGameObjectsWithTag already loops only through active objects.
//Note objectHashSetDatabase can have up to 200+ active objects AI
foreach (GameObject object in objectHashSetDatabase )
{
if(object.tag == “Police”)
//Check for distance and then act
if(object.tag == “Something else”)
}
You need to look into spatial partitioning systems to ease the workload. A short summary of the idea:
Split your scene into a number of cells (cubes if 3D, squares if 2D) and store those in a multidimensional array. An AI is always a member of a cell, corresponding to the area of the scene the AI currently occupies. When an AI moves, update its cell membership.
Now, in the above, you no longer have to test distance against every single gameobject. It is enough to test against a cell since, if the distance to a cell exceeds whatever threshold you define, you can assume the same counts for all members of the cell. This allows you to skip calculations for each of the members, which becomes expensive with great numbers, as you’ve noticed.
If the distance to a cell does not exceed your defined threshold, you need to treat the cell’s members individually.
The science now is to choose cell size wisely such that a reasonable tradeoff between cell iteration and member iteration becomes faster than simply iterating over all AIs.
Many algorithms in computer graphics use various versions of spatial partitioning including, but not limited to, ray casting, collision detection and occlusion culling.