so i have a npc system that’s functioning pretty well… when there’s only one of them. the issue is that when there’s 50 of them, the server lags a ton due to the amount of stuff happening frequently in loops. how would i go about managing lots of npcs without slowing down the server? code is below(by the way the humanoid of the enemy is named “Enemy”)
local Root = script.Parent.HumanoidRootPart
local Range = 100
local Damage = 30
local HitHumanoids = {}
script.Parent.Enemy.Touched:Connect(function(Hit)
local Humanoid = Hit.Parent:FindFirstChildOfClass("Humanoid")
if Humanoid and script.Parent.Enemy.Health > 0 and Humanoid.Name ~= "Enemy" and not HitHumanoids[Humanoid] then
HitHumanoids[Humanoid] = true
Humanoid:TakeDamage(Damage)
wait(1)
HitHumanoids[Humanoid] = false
end
end)
script.Parent.Enemy.Died:Connect(function()
wait(3)
script.Parent:Destroy()
end)
game:GetService("RunService").Heartbeat:Connect(function()
local Target = nil
local targettable = {}
for i,v in pairs(game.Workspace:GetDescendants()) do
if v:IsA("Humanoid") and v.Name ~= "Enemy" then
table.insert(targettable,v.Parent.PrimaryPart)
end
end
for i,Part:Part in pairs(targettable) do
local Humanoid = Part.Parent:FindFirstChildOfClass("Humanoid")
if Humanoid and Humanoid.Health > 0 and Humanoid.Name ~= "Enemy" then
local Distance = (Root.Position - Part.Position).Magnitude
if not Target and Humanoid.Health > 0 then
Target = Part
end
if (Root.Position - Target.Position).Magnitude > Distance and Humanoid.Health > 0 then
Target = Part
end
end
end
if Target and (Root.Position - Target.Position).Magnitude <= Range then
if Target.Position.Y > Root.Position.Y+8 then
script.Parent.Enemy.Jump = true
script.Parent.Enemy:MoveTo(Target.Position, Target)
else
script.Parent.Enemy:MoveTo(Target.Position, Target)
end
end
end)