How to stop the loop when the player is away from the mob, and run when player gets closer?

local Players = game:GetService("Players")

local Mob = script.Parent
local Enemy = Mob:FindFirstChildOfClass("Humanoid")
local mtemp = Mob.HumanoidRootPart	

local _M = require(Mob:WaitForChild("MobConfig"))

local dist = _M.FollowDistance
local distnear = _M.FollowNear

FindNearestTorso = function()

for _,v in pairs(Players:GetPlayers()) do		
local chr = v.Character
if chr and chr:FindFirstChild("HumanoidRootPart") and Mob:FindFirstChild("HumanoidRootPart") then	
local temp = chr.HumanoidRootPart	
local human = chr.Humanoid		
			
if human.Health > 0 and (temp.Position - mtemp.Position).Magnitude < dist then	
local HRoot = temp
local hum = human			
Enemy:MoveTo(HRoot.Position - CFrame.new(mtemp.Position, HRoot.Position).LookVector * distnear)	
end
end
end
end
	
while true do
FindNearestTorso()
wait(_M.FollowDelay)	
end

I have multiple mobs so they are poor performance because many loop scripts work.

Have the loop as a function and call it whenever a player gets within the range. Inside the loop you can check if the distance from your target is less then x else break.

function loop()
— you would have a for loop instead

if mag < Argo then
—ur code to move the np to the target
else
break
end

end

while wait(1) do
if mag < agro then — check if target is close enough
loop() — ur loop function
end
end

Thank you so much, this really works.
(You forgot to put wait() inside the loop)

1 Like