While Wait Loop

My aim is to make the NPC move to a random location every 1 to 7 seconds. My issue is that the code is being repeatedly executed. I’m assuming that I could utilise a debounce but I might be wrong.

Here is the code:

		while CustomWait(math.random(1,7)) do
		
		print("While loop started")
		
		if moveRandomly == true then
			
			local newLocation
		do repeat
				newLocation = randomLocations:FindFirstChild(math.random(1, 10))
				CustomWait()
			until
			newLocation ~= randomLocation
		end
		path:ComputeAsync(humRootPart.Position, newLocation.Position)
		local wayPoints = path:GetWaypoints()

		for i, wayPoint in pairs(wayPoints) do
				humanoid:MoveTo(wayPoint.Position)
			humanoid.MoveToFinished:Wait()
		end
		
		humanoid:MoveTo(newLocation.position)
			humanoid.MoveToFinished:Wait()

What should I do? Thanks for any help.

2 Likes

What is the CustomWait function? It might be preventing the loop from pausing.
Putting the wait within the loop might work.

while true do
    -- code happens here
    task.wait(math.random(1, 7))
end

–Heres my Thoughts

while true do

local CustomWait = math.random(1,7)

wait(CustomWait)

	print("While loop started")
	
	if moveRandomly == true then
		
		local newLocation
	do repeat
			newLocation = randomLocations:FindFirstChild(math.random(1, 10))
			CustomWait()
		until
		newLocation ~= randomLocation
	end
	path:ComputeAsync(humRootPart.Position, newLocation.Position)
	local wayPoints = path:GetWaypoints()

	for i, wayPoint in pairs(wayPoints) do
			humanoid:MoveTo(wayPoint.Position)
		humanoid.MoveToFinished:Wait()
	end
	
	humanoid:MoveTo(newLocation.position)
		humanoid.MoveToFinished:Wait()

In this case, I’m pretty sure a debounce would be essential.

1 Like

Do you think that I could remove the while wait loop and just have and if statement that keeps running. I could then do:

local debounce = false
	
		if moveRandomly == true and debounce == false then
			debounce = true
		
			local newLocation
		do repeat
				newLocation = randomLocations:FindFirstChild(math.random(1, 10))
				task.wait()
			until
			newLocation ~= randomLocation
		end
		path:ComputeAsync(humRootPart.Position, newLocation.Position)
		local wayPoints = path:GetWaypoints()

		for i, wayPoint in pairs(wayPoints) do
				humanoid:MoveTo(wayPoint.Position)
			humanoid.MoveToFinished:Wait()
		end
		
		humanoid:MoveTo(newLocation.position)
			humanoid.MoveToFinished:Wait()
			
		elseif moveRandomly == false and debounce == false then
			
			debounce = false

Depends what you’re trying to do. If you’d want a constant delayed iteration, I’d recommend using the while loop otherwise the if statement should work too, if persistently called as a function.

if moveRandomly == true then

Is this ever switched to false and never back to true again? Track your ‘state’ variables and make sure their values are as expected.