Basically, I have a turret. I want to know when an object named 'Enemy' is 3 or less studs away from it. If it is, it casts a ray (Don't worry about that, I know how to raycast). Is there an efficient way to do this? Here's what I've got so far:
while wait() do
for _,v in pairs(game.Workspace:GetChildren()) do
if string.lower(v.Name) == "enemy" then
local distance = (script.Parent.Position-v.Position).magnitude
if distance <= 3 then
-- code
end
end
end
end
I would just like to know if there's a more efficient way to do this. This seems like there might be, although this is the only thing I've come up with.

2 comments
You might be able to give the turret a cool down time. So the turret would fire for a specific amount of time and then cool down before firing again. I would make sure that the turret fired long enough to completely kill one target. I would also target the same enemy until cooldown or until that enemy is dead.
Yes, but I mean let's say I want to have other code inside of that same script. It won't run since that while wait() statement is running. Is there a way to detect when the enemy gets close to the turret without using a while loop?