Help needed with damage dealing of npc's and detecting player in a certain distance

Hello Robloxians, I have a issue with my script where i need it to detect a player within a certain radius and then go there. and a issue with how my bear NPC does more damage towards players.

here is my code:

local RunService = game:GetService("RunService")
local Players = game:GetService("Players")

local humanoid = script.Parent
local root = humanoid.Parent.PrimaryPart

local targetDistance = script:GetAttribute("TargetDistance")
local stopDistance = script:GetAttribute("StopDistance")
local damage = script:GetAttribute("Damage")
local attackDistance = script:GetAttribute("AttackDistance")
local attackWait = script:GetAttribute("AttackWait")
local lastAttack = tick()

function findNearestPlayer()
	local playerList = Players:GetPlayers()
	
	local nearestPlayer = nil
	local distance = 30 ---does not work for some reason.
	local direction = nil
	
	for _, player in pairs(playerList) do
		local character = player.Character
		if character then
			local distanceVector = (player.Character.HumanoidRootPart.Position - root.Position)
			if not nearestPlayer then
				nearestPlayer = player
				distance = distanceVector.Magnitude
				direction = distanceVector.Unit
			elseif distanceVector.Magnitude < distance then
				nearestPlayer = player
				distance = distanceVector.Magnitude
				direction = distanceVector.Unit
			end	
		end
	end
	
	return nearestPlayer, distance, direction
end

RunService.Heartbeat:Connect(function()
	local nearestPlayer, distance, direction = findNearestPlayer()
	if nearestPlayer then
		if distance <= targetDistance and distance >= stopDistance then
			humanoid:Move(direction)
		else
			humanoid:Move(Vector3.new())
		end
		
		if distance <= attackDistance and tick() - lastAttack >= attackWait then
			lastAttack = tick()
			nearestPlayer.Character.Humanoid.Health -= damage
		end
	end
end)

if you have any idea why this is not working please let me know.
all help is apreciated