How can I end a loop in a function?

I’m trying to create an enemy that chases after the player, but before he sees the player he will be moving towards two parts. How could I end that loop inside another function?

local RunService = game:GetService("RunService")
local Players = game:GetService("Players")

local humanoid = game.Workspace.SecondMap.NPCS.Guard.Humanoid
local root = humanoid.Parent.PrimaryPart

local targetDistance = 20
local stopDistance = 5

local enemyIdle = true

while enemyIdle do
	wait()
	humanoid:MoveTo(game.Workspace.SecondMap.GuardParts.Part1.Position)
	humanoid.MoveToFinished:Wait()
	wait()
	humanoid:MoveTo(game.Workspace.SecondMap.GuardParts.Part2.Position)
	humanoid.MoveToFinished:Wait()
	wait()
end

function findNearestPlayer()
	local playerList = Players:GetPlayers()
	
	local nearestPlayer = nil
	local distance = nil
	local direction = nil
	
	for _, player in pairs(playerList) do
		local character = player.Character
		if character then
			local distanceVector = (player.Character.HumanoidRootPart.Position - root.Position)
			if not nearestPlayer then
				nearestPlayer = player
				distance = distanceVector.Magnitude
				direction = distanceVector.Unit
			elseif distanceVector.Magnitude < distance then
				nearestPlayer = player
				distance = distanceVector.Magnitude
				direction = distanceVector.Unit
				enemyIdle = false
			end
		end
	end
	
	return nearestPlayer, distance, direction
end

RunService.Heartbeat:Connect(function()
	local nearestPlayer, distance, direction = findNearestPlayer()
	if nearestPlayer then
		if distance <= targetDistance and distance > stopDistance then
			humanoid:Move(direction)
		else
			humanoid:Move(Vector3.new())
		end
	end
end)
2 Likes

You can use the task library in order to run the loop in a thread then cancel the thread when you’d like to stop the loop

If it’s a RunService loop you can disconnect the connection to stop it

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.