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
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