Why is this code severely decreasing server performance?

Hello developers,

I have been stuck on this for a while now because having this code completely lags the server which is a major issue as it slows everything down. I have made multiple posts about this but i have yet to get a solution to this issue.

Basically, i am making a game where enemies will come towards a base and players can place troops to kill them before they get too close (essentially something like tds). However, the issue that i am having is, if this script is running while there are around 30+ enemies spawned in, it causes the server to lag a bunch.

Obviously, since there are enemies and the troops need to detect if the enemies are in range and which is the closest, that means everytime the troops cooldown has finished it would do a complete loop through the folder of enemies to find which is the closest to the troop (i think this is the reason of the issue)

So my question is, is there any way to fix this problem? (the code i made for the attacking is shown below). Some people have suggested that i make a part around the troops and use :GetTouchingParts but there is a major issue with using this idea as the troops will have multiple tiers that can upgrade the range etc so it would be a hastle of changing the size of that part.

Below is the code for the troops attacking the enemies

function Attack()
	local target = attackModule.LocateTarget(script.Parent.Parent.Parent, range)

	if game.Workspace.GameValues.RaidOngoing.Value == false then ToggleLasers(nil) return end
	if script.Parent.Parent.Parent.Stunned.Value == true then ToggleLasers(nil) task.wait(1) return Attack() end
	if target then else ToggleLasers(nil) task.wait(0.5) return Attack() end

	if target and target:FindFirstChild("HumanoidRootPart") and target.Humanoid and target.Humanoid.Health > 0 then
		game.ReplicatedStorage.Events.LookToTarget:Fire(target.HumanoidRootPart.Position)
	end	

	if target and target.Humanoid and target.Humanoid.Health > 0 then
		attackModule.DamageTarget(target, damage)
		script.Parent.Parent.Parent.Fire:Play()
		ToggleLasers(target)
	end	
	task.wait(cooldown)
	return Attack()
end

game.Workspace.GameValues.RaidOngoing.Changed:Connect(function(val)
	if val == true then Attack() end
end)

Below is the code for detecting the closest enemy/target

for i, v in ipairs(workspace.RaidStuff.RaidEnemys:GetChildren()) do
	if v:FindFirstChild("HumanoidRootPart") and v:FindFirstChild("Humanoid") and v:FindFirstChild("Humanoid").Health > 0 then
		local distance = (v.HumanoidRootPart.Position - currenttowerhrp.Position).Magnitude
		if distance < range then
			target = v
			range = distance
		end
	end
end

Thank you for reading and any support is massively appreciated!

1 Like

Why?

After the function has finished, it will wait the cooldown and then do return Attack() to restart is basically just so i can loop it. Then once the function has restarted it can check if there are any enemies and if not then it can return and end the function entirely. I thought that this way would be more effecient that while wait() do as it only runs when needed.

Assuming your assumption about where the performance problem is is correct, then you might try a different approach:

In while loop or RunService heartbeat (I prefer RunService), capture the current position of each enemy and cache it in a table in memory.

Key note: make sure to throttle this caching …to like 1 second or something to avoid the looping frequently and causing the performance problem.

Then your troops only have to read through the array of cached positions to find the closest.

I won’t write the code for you but I’d bet it’ll solve the problem IF the performance issue is in the loop as you say.

[edit addition] This could probably even be optimized further to handle change detection on the incoming enemies movements.

Can you use task.spawn(Attack) ? That way it will run the function in a new thread so you don’t have to wait for Attack() to return.
I’m not entirely sure if it will solve the lag but it may be worth a try.

You can also try to run some of the code on the clients side using Remote Events or Remote Functions so it won’t put too much load on the server.