As you can see, you may recognize this script from old zombie models that are instructed to follow you. However, I can't find any way to make this run faster, because if there are too many models using this script, the game runs too slow. I've tried making the loop slower and doesn't work.
local larm = script.Parent:FindFirstChild("Left Arm")
local rarm = script.Parent:FindFirstChild("Right Arm")
function findNearestTorso(pos)
local list = game.Workspace:children()
local torso = nil
local dist = 100
local temp = nil
local human = nil
local temp2 = nil
for x = 1, #list do
temp2 = list[x]
if (temp2.className == "Model") and (temp2 ~= script.Parent) then
temp = temp2:findFirstChild("Torso")
human = temp2:findFirstChild("Humanoid")
local player = game.Players:GetPlayerFromCharacter(temp2)
if not player and (temp ~= nil) and (human ~= nil) and (human.Health > 0) and human.Parent.Name ~= "Zombie" then
if (temp.Position - pos).magnitude < dist then
torso = temp
dist = (temp.Position - pos).magnitude
end
elseif player and (temp ~= nil) and (human ~= nil) and temp.Transparency ~= 1 and (human.Health > 0) and player.TeamColor ~= BrickColor.new("Bright green") then
if (temp.Position - pos).magnitude < dist then
torso = temp
dist = (temp.Position - pos).magnitude
end
end
end
end
return torso
end
while true do
wait(1)
local target = findNearestTorso(script.Parent.Torso.Position)
if target ~= nil then
script.Parent.Humanoid:MoveTo(target.Position, target)
end
end
