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.
The best way to do this is to use a coroutine.
Info: Beginners Guide to Coroutines, Coroutine manipulation, and Lua Corountine
local Run = coroutine.wrap(function() 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 end) Run() -- Run will not yield --More code here