Script breaks after a couple of minutes

Alright so im a bit stumped on this. So I am currently making a non humanoid pathfinding npc, However the script tends to break after a certain period of time. And its mostly for all of the NPCS, If I try to reinsert another. It breaks as well. Im a bit confused on this. Can someone tell me what im doing wrong?

-- code
local part = script.Parent
local force = script.Parent:WaitForChild("Force")

local pathfind = function(start,finish)
	local path = game:GetService("PathfindingService"):ComputeRawPathAsync(start,finish,500)
	return path:GetPointCoordinates() 
end


while true do
	wait()
	local positions = pathfind(part.Position,script.Parent.Parent.Parent.Finish.Position)
	local oldPos = script.Parent.Parent.Parent.Finish.Position
		for _,pos in next, positions do
			force.position = pos
			repeat
				wait()
		until (part.Position - pos).magnitude < 2 or (oldPos - script.Parent.Parent.Parent.Finish.Position).magnitude > 5
		script.Parent.BodyGyro.CFrame = CFrame.new(script.Parent.Position , Vector3.new(pos.X, script.Parent.Position.Y, pos.Z))
		if (oldPos - script.Parent.Parent.Parent.Finish.Position).magnitude > 5 then break end
		end
end

Um, Ozzypig. Im a bit confused on what you mean.

I edited your post to wrap your code inside backticks so it shows up with syntax-highlighting. It helps others read your code easier which helps you get the advice you need :slight_smile:

oh ok thanks, But is there anyway to fix my code?

I’m gonna skip the lecture on why you should use while true do wait() ... end loops.

Perhaps it’s breaking because it sometimes is unable to find a path from one point to another. It doesn’t look like your code accounts for this scenario - so maybe that’s a good place to start debugging. It helps immensely if you can get your code to produce an error.

alright, im gonna run the code again and see if theres an error.

aw man. nothing there, Not even if the path is unaccessible.

but about the while true do thing, Is there anything else I could use instead of while true do? im a bit new to coding.