- Home /
Efficient way to scan surrounding with large number of objects
Hello,
I am working on a personal ant colony simulation project and I am struggling with performance.
I have a bunch of agents (ants) in the scene and I need each of them individually to scan their surrounding in some area. For now I am using Physics.OverlapSphere to get the objects around them. The problem is I need to get the type of the object there is and perform some action based on the type and their count.
For that I haven't found another way than to call .GetComponent() on the Collider. As you may already guess, this is really inefficient, since I'm calling this in every Update of each Ant and the possible Collider objects are all other ants in the scene, as well as different pheromones dropped on the ground (which there are order of magnitude more of than ants), so there are thousands of interactions and GetComponent calls each frame.
I have tried moving the "Scan" out from Update into a Coroutine which is triggered on random intervals instead of every Update, which helped, but not a lot.
I have also improved the performance a bit by using LayerMasks for the OverlapSphere, but it's again negligible.
I'm aiming to have thousands of ants in the scene, and the framerate drops to unacceptable levels even with 100+ now. The scene is pretty much empty otherwise.
I have also considered moving to Dots/ECS, but I found out that the Physics can be triggered from the main thread only anyway, so I'm not sure that would be of much help. Is this correct assumption?
Any suggestions? Even outside of the box ones are welcome. I am even failing to grasp how Unity handles 1000+ (MonoBehaviour) agents in the scene in general.
Another thing I considered is to move all the "non-ant" object to a "virtual" plane (some structure like 2D array) and do the scanning by coordinates there by hand with some hand-made algorithm (like quad-tree) but it seems like a lot of work for questionable results (doubtful I could make it more efficient than Unity's built-in Physics library functions).
PS: I am sure the culprit of the performance is where I say, see the profiler snippet: (EditorLoop is 32%+, 10% is Camera.Render)
PPS: If this was better suited for Forums rather than Answers, please tell me, I was not sure.