Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

More efficient way to detect enemies near turret?

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

0

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.

0

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?

1 answer

✓ Accepted answer

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

This discussion is preserved as it was. New answers, comments, and votes are closed.