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!