NPC's randomly stop moving

Hello!

Today I was working on a humanoid walking system, it works perfectly fine. But, after around 1 - 6 different move functions called, it stops and just stays at its last destination.
image image

Server Script
--[NPC HANDLER]

local NPCAmount = 0
local MaxNPCAmount = 40

NPCsFolder.ChildAdded:Connect(function(Child)
	setCollisionGroupRecursive(Child, NPCCollisionName)
	if Child:FindFirstChild("Humanoid") then
		NPCAmount = NPCAmount + 1
	end
end)

NPCsFolder.ChildRemoved:Connect(function(Child)
	if Child:FindFirstChild("Humanoid") then
		NPCAmount = NPCAmount - 1
	end
end)

coroutine.resume(coroutine.create(function()
	while wait(1) do
		if MaxNPCAmount >= NPCAmount then			
			spawn(function()
				NPCHandler.NewNPC()
			end)
		end
	end
end))
Module Script
--[MODULAR]

local module = {}

function module.NewNPC()
	local Destination = Workspace.Pathfinding.Spawns:GetChildren()[Rand:NextInteger(1, #Workspace.Pathfinding.Spawns:GetChildren())]
	local NewNPC = ServerStorage.NPCs:GetChildren()[Rand:NextInteger(1, #ServerStorage.NPCs:GetChildren())]:Clone()
	NewNPC.Parent = Workspace.NPCs
	NewNPC:SetPrimaryPartCFrame(Destination.CFrame + Vector3.new(0, 2, 0))
	MoveNPC(NewNPC)
end

function MoveNPC(NPC)
	
	local Humanoid = NPC.Humanoid
	local Distance
	
	local Destination = Workspace.Pathfinding.Pathways:GetChildren()[Rand:NextInteger(1, #Workspace.Pathfinding.Pathways:GetChildren())]
	local Path = PathfindingService:CreatePath()
	Path:ComputeAsync(NPC.PrimaryPart.Position, Destination.Position)
	
	local Waypoints = Path:GetWaypoints()
	
	for i, Waypoint in pairs(Waypoints) do
		Humanoid:MoveTo(Waypoint.Position)
		if not NPC:FindFirstChild("HumanoidRootPart") or not NPC:FindFirstChild("Humanoid") or not NPC then
			break
		end
		repeat 
			if not NPC:FindFirstChild("HumanoidRootPart") or not NPC:FindFirstChild("Humanoid") or not NPC then
				break
			end
	   		Distance = (Waypoint.Position - NPC.PrimaryPart.Position).Magnitude
	    	wait()
	    until
		    Distance <= 5
			if (NPC.PrimaryPart.Position - Destination.Position).Magnitude <= 5 then
				wait(0.1)
				MoveNPC(NPC)
		end
	end
	
end
1 Like

MoveNPC has to be defined above module.NewNPC for you to be able to call it within that function.

No, it isn’t a local function.

Perhaps this is affecting it?

The reach goal state of a humanoid will timeout after 8 seconds if it doesn’t reach its goal. This is done so that NPCs won’t get stuck waiting for Humanoid.MoveToFinished to fire. If you don’t want this to happen, you should repeatedly call MoveTo so that the timeout will keep resetting.

4 Likes