Get Line of Sight from multiple objects performance

Hi all,

So I’m working on a little pet project where I’m trying to get large scale melee battles working. I’m trying to get each entity to check its current area, get what is in its field of view and then shoot a ray to actually see if we can see the object and it is not blocked by anything, here’s what I have.

Collider[] cols = Physics.OverlapSphere(transform.position, 30);
foreach(Collider c in cols)
        {
            if (c.gameObject.tag == Tags.zombie)//narrow down to this tag
            {
                //get direction to target
                Vector3 toTarget = (c.gameObject.transform.position - transform.position);
                //check if its in front of this entity
                if(Vector3.Dot(toTarget.normalized,transform.forward)>0)
                {
                    RaycastHit hit;
                    Ray ray = new Ray(transform.position + transform.up, toTarget);
                    if(Physics.Raycast(ray,out hit,30))
                    {
                        Debug.DrawLine(transform.position, hit.point);
                    }
                }
            }
        }

It works fine for the most part, I can return the distance of the RaycastHit to find the closest object and sort out which is the best to attack etc. However when I push the amount of entities up to around 3-400 units I get huge framerate drops. I’ve already gone through the process of creating a physical collider to catch anyone in sight but this was massively slower than what I currently have. I’ve also thought about using layermasks to filter the casts but I’m not sure that’s what is eating up memory.

Is there a less CPU intensive way to do this?

If you want hundreds of autonomous agents, optimization is the name of the game. Frankly I wouldn’t expect you to get good performance with that many agents without some serious kung-fu and a major reality-check on expectations.

By this I mean some kind of masterfully optimized routine that handles all agent interaction in a highly efficient and sophisticated way, and does not attempt to execute any complex logic on a per-unit basis.

Something like the total-war franchise with their zillions of units absolutely do not give units any autonomy. Individual unit actions are directed by the most simplistic means possible; director oversight. They are treated like particles and organized and orchestrated by the absolute simplest math that will produce a pleasing result.

In any event, to even approach such numbers of agents, you must limit the number and frequency and complexity of every last function in their AI routines. No per-frame per-unit awareness or line-of-sight checks, for one thing. That’s a non-starter right off the bat. With 50 units? Maybe. 100? Possibly. 500? Noooooo way. :wink: