Best way to periodically search for NPCs?

Hello,

I’m trying to implement a Part that searches for nearby players. I want to use CollectionService to tag parts that will have this functionality. Here is my code:

local CollectionService = game:GetService("CollectionService")

local function lookForPlayers(enemy)
	while true do
		print(enemy)
		--lf players: raycast, proximity check, etc
		wait(1)
	end
end


CollectionService:GetInstanceAddedSignal("Enemy"):Connect(function(enemy)
	local f = coroutine.wrap(lookForPlayers)
	f(enemy)
end)

Is this a good implementation? How performant is this compared to other solutions?

Thanks

To be honest, one of the easiest methods that doesn’t stress too much the server is using a big sphere or block part on the NPC’s position and check when a player touches it with a .Touched event. That’s how I made my NPCs spawn/despawn if there’s a player nearby.

As long as you aren’t firing for example 100 long rays per second you should be fine.