Laggy/Stuttering NPC Walking

oh ya sorry


local function PatrolToRandomSpot(targetFloor, friendly)
	if not targetFloor then return end

	local floorSize = targetFloor.Size
	local floorCFrame = targetFloor.CFrame

	local randomX = (math.random() - 0.5) * floorSize.X
	local randomZ = (math.random() - 0.5) * floorSize.Z

	local targetPosition = floorCFrame.Position + Vector3.new(randomX, 3, randomZ) -- slightly above floor

	pcall(function()
		NPC.PrimaryPart:SetNetworkOwner(nil)
	end)

	StartPathTo(targetPosition)

	local detectionDistance = 50
	local playerDetected = false

	-- Path recovery
	local blockedConnection = Path.Blocked:Connect(function()
		StartPathTo(targetPosition)
	end)

	local errorConnection = Path.Error:Connect(function()
		StartPathTo(targetPosition)
	end)

	-- Loop check instead of Heartbeat
	while not playerDetected and isPathfinding do
		if IsPlayerNearby(detectionDistance, friendly) then
			playerDetected = true
			state = "Aggressive"
			break
		end
		task.wait(0.2)
	end

	-- Cleanup
	if blockedConnection then blockedConnection:Disconnect() end
	if errorConnection then errorConnection:Disconnect() end

	if not playerDetected then
		task.wait(math.random(2, 5))
	end
end

Also there are a lot of humanoids that are owned by the server, like maybe a hundred cause there are animals and such, does that play a factor?