Help! Loop is not repeating!

You can write your topic however you want, but you need to answer these questions:

  1. What do you want to achieve? Keep it simple and clear!
    I want my NPC pathfinding loop to keep repeating iteslf.
  2. What is the issue? Include screenshots / videos if possible!
    The loop runs twice and prints “Repeat” and “Cloned”, but when the loop repeats the third time, it only prints “Repeat”.
  3. What solutions have you tried so far? Did you look for solutions on the Developer Hub?
    I have tried debugging the code and looked for errors, but I didn’t find any. I looked on the forum for similar problems like loops not repeating, but that didn’t show any results either.
    After that, you should include more details if you have any. Try to make your topic as descriptive as possible, so that it’s easier for people to help you!
    My script is on the bottom and shows what I have done so far. If you notice anything wrong please reply!
local pathfindingservice = game:GetService("PathfindingService")

local path = pathfindingservice:CreatePath()

local NPC = game.ReplicatedStorage.ReturnNpcs:GetChildren()

for i, v in pairs(NPC) do
	
	local NPCNumber = math.random(1, 2)
	
	local chosenNPC = NPC[NPCNumber]:Clone()
	
	print("Cloned")
	
	chosenNPC.Parent = game.Workspace
	
	local returnanimation = script:WaitForChild("BookReturn")
	
	local humanoid = chosenNPC:WaitForChild("Humanoid")
	
	local returnbook = humanoid:LoadAnimation(returnanimation)
	
	local walkanimation = script:WaitForChild("Walk")
	
	local walk = humanoid:LoadAnimation(walkanimation)
	
	path:ComputeAsync(chosenNPC.HumanoidRootPart.Position, game.Workspace.Finish.Position)
	
	local waypoints = path:GetWaypoints()
	
	if humanoid.WalkSpeed > 0 then
		walk:Play()
	end
	
	for i, v in pairs(waypoints) do
		local part = Instance.new("Part")
		part.Size = Vector3.new(2,2,2)
		part.Position = v.Position
		part.Anchored = true
		part.Transparency = 1
		part.CanCollide = false
		part.Parent = game.Workspace.Waypoints
	end
	
	for i, v in pairs(waypoints) do
		chosenNPC.Humanoid:MoveTo(v.Position)
		chosenNPC.Humanoid.MoveToFinished:Wait()
	end
	
	walk:Stop()
	wait(3)
	returnbook:Play()
	wait(3)
	chosenNPC:Destroy()
	wait(3)
	print("Repeat")
	
end

You don’t have a repeating loop
Use repeat until
or
while (true) do end

The loop you are using has a set amount so it will not keep going unless you have infinite npc

Loop Information:

2 Likes

You are using what is called a “Generic Loop”. You cannot make this run forever. It iterates dependent on how many NPC instances there are. To fix this wrap the generic loop in an infinite loop.

1 Like

@CodeAnomaly and @Diamond_Plus1 thank you! I didn’t notice this issue and learned that it could be solved easily by just adding a simple while true do. My script now works perfectly and is repeating itself every time! Once again thank you!