# Best way to constantly get nearby enemies?

For performance reasons, on the client, I want to only show enemy models if they’re close to the player, otherwise I am going to make them invisible. For context, there are going to be hundreds of enemies across the whole server at once.

One solution, would be to do a distance check on every single enemy, every .1 seconds. But that’s not ideal, nor is it efficient.
Another, would be to use GetPartBoundsInRadius, with the OverlapParams set to the enemies’ hitboxes in the whitelist, every couple seconds, and then doing distance checks on what that gathered every .1 seconds. This solution is probably closest to the best way, but I feel like there’s a better way.

I’m looking for the best, most efficient way I should be doing this. I’m open to using complex algorithms if any of you know any that works.

1 Like

You need to use a grid, a grid is a table organized by Cells via X,Z (Y axis too if you want it 3d but often not nessc.)

https://gyazo.com/c9fc7663d87a57bec104f86291017d91.mp4
Here is an example video of one I made, the white squares represent cells that are in the grid, and the pink cells represent the cells that it’s looking in (Like for detecting enemies ie; sense range)

Searching for a cell is a 1 time math operation, so its very efficient and with this method instead of looping through every possible enemy your only looping through nearby cells (realistically these cells would be big like 50x50 studs, instead of the small ones in the video)

WIth this method I was able to simulate 200 zombies with pathfinding code (from few years ago) with no performance issues

For more indepth help you can contact me on discord Thedagz#4176

https://developer.roblox.com/en-us/api-reference/function/WorldRoot/FindPartsInRegion3

Then just determine by using the “Position” properties and calculating magnitude.