I have an NPC with a gun welded to his hand. Everyting about that is perfect. the gun is just a part, nothing inside. So i want it so if the player is in range and the player is not behind a wall or object, the npc's bullets hurt the player.

Iv tried a script that detects the closest player in a range, which works perfectly for other scripts, and then i used a while true do loop to fire until out of bullets, then npc reloads and contonues to shoot, but so far he never does damage.

script i tried:

ammo = 7
clips = 7--double clip in both pockets (4), two in jacket (2), one in pistol (1) 4+2+1 = 7 clips

function detect_closest_user(radius)
	local everyone_in_radius = {}
	for i, v in pairs(game.Players:GetChildren()) do
		if (script.Parent.Parent.HumanoidRootPart.Position - v.Character.Torso.Position).magnitude <= radius then
			table.insert(everyone_in_radius, v.Character)
		end
	end
	if #everyone_in_radius > 1 then
		return everyone_in_radius[math.random(1, everyone_in_radius)]
	elseif #everyone_in_radius == 1 then
		return everyone_in_radius[1]
	elseif #everyone_in_radius == 0 then
		return nil
	end
end--ALL OF THIS is the closest player in a rangte script, below is while true do loop



while true do
	wait(1)
	if ammo > 0 then
		script.Parent.Parent.Gun.fire:Play()
		ammo = ammo - 1
		local ray = Ray.new(script.Parent.Parent.Head.Position, (detect_closest_user(1000).HumanoidRootPart.Position))
local part = workspace:FindPartOnRay(ray, script.Parent.Parent, true, true)
if part then
	if part.Parent:FindFirstChild("ImACriminal") then
		detect_closest_user(1000).Humanoid:TakeDamage(25)
	end
	end
	elseif ammo <= 0 then
		wait(1)
		script.Parent.Parent.Gun.recoil:Play()
		wait()
		wait(.5)
		ammo = 7
	end
end

as you can see, i tried a ray that goes from NPC head to player's humanoidrootpart, but doesn't do damage. and the ImACriminal thing is something inside the player always, so don't suspect a thing about that.

please help, thanks!