New: Nitro Boost our Discord server and receive full donation perks here on the website! Join the Scripting Helpers Discord Server to learn more! You can also Support on Patreon as always.
Still have questions? Join our Discord server and get real time help.
0

# The script lags a lot and I don't know why, help?

I am trying to make an NPC follow the nearest player it can find, however it lags a lot and i dont want this to happen, please help, my code:

Distance = 250

while wait() do
for i,Model in pairs(game.Workspace:GetChildren()) do
if Model.ClassName == "Model" and Model ~= script.Parent then
Humanoid = Model:FindFirstChild("Humanoid")
if Humanoid ~= nil then
if Humanoid.Health > 0 and Humanoid.Parent.Name ~= script.Parent.Name then
Torso = Humanoid.Parent:FindFirstChild("Torso")
if Torso ~= nil then
if (Torso.Position - script.Parent.Torso.Position).Magnitude < Distance then
script.Parent.Humanoid:MoveTo(Torso.Position)
end
end
end
end
end
end
end

0
When is this script meant to be triggered? palav 104 — 11d
0
This script is meant to go inside an NPC to make it follow a player, it triggers instantly and works but lags and I can't figure out why Lord_WitherAlt 55 — 11d

0
void_node 753
11 days ago
Edited 9 days ago

try this:

local Players = game.Players
local current_torso;
local NPC_torso = script.Parent.HumanoidRootPart

while wait() do
for _, player in pairs(Players:GetPlayers()) do
local char = player.Character
local root_part = char.HumanoidRootPart
if not current_torso and char then
current_torso = root_part
elseif(char ~= current_torso.Parent and char) then
local magnitude = (root_part.Position - NPC_torso.Position).Magnitude
local old_magnitude = (current_torso.Position - NPC_torso.Position).Magnitude

if(magnitude < old_magnitude) then
current_torso = root_part
end

end
NPC_torso .Parent.Humanoid:MoveTo(current_torso.Position)
wait();
end
end



i am at school so forgivee me for errors

0
Yea I am at school too. TheLastHabanero 231 — 11d
0
If your answer works, I will accept it, can't test right now, maybe not till tomorrow, see if you can run it without lag, I will test it when I get back to my pc Lord_WitherAlt 55 — 10d
0
It doesnt work, it lags like my script Lord_WitherAlt 55 — 10d
0
umm in this case then the lag is in another script, b/c it worked with no problem when i tested it void_node 753 — 9d