Function not firing in for loop

Im trying to have this function run one time once the event is fired, It works without the if detected ==false then but once I add it, it just stops working as if to mock me and despite my best efforts of persuasion, it refuses to cooperate. Can anyone help me stop my code from misbehaving? Thank you.

local players = game:GetService("Players")
local funnyMen = collectionService:GetTagged("Enemy")
local detected = false

local function funnyFunc(funnyMan)
	local nearestPlayer, nearestDistance
	for _, player in pairs(players:GetPlayers()) do
		local character = player.Character
		local distance = player:DistanceFromCharacter(funnyMan.HumanoidRootPart.Position)
		if not character or 
			distance > maxDistance or
			(nearestDistance and distance >= nearestDistance)
		then
			continue
		end
		nearestDistance = distance
		nearestPlayer = player
	end
	if nearestPlayer then
		funnyMan.PrimaryPart.CFrame = CFrame.new(funnyMan.PrimaryPart.Position, Vector3.new(nearestPlayer.Character.PrimaryPart.Position.X, funnyMan.PrimaryPart.Position.Y, nearestPlayer.Character.PrimaryPart.Position.Z))
	end
end

for i,v in pairs(funnyMen) do
	local detectEvent = v:FindFirstChild("Detect")
	detectEvent.OnServerEvent:Connect(function()
		if detected == false then
			funnyFunc(v)
			detected = true
		end
	end)
end

The problem is that you using 1 variable “detected” to check all the funnyMen if you use this code each funnyMen will follow the nearest person 1 time and after that it will not follow anyone anymore.

I changed the detected variable that is global for all the funnyMen to local for each one.

for i,v in pairs(funnyMen) do
        local detected = false
	local detectEvent = v:FindFirstChild("Detect")
	detectEvent.OnServerEvent:Connect(function()
		if detected == false then
			funnyFunc(v)
			detected = true
		end
	end)
end

if you wanna that the funnyMens after following the nearest person follow other one you need to change the value detected again to false with a delay or after the funnymen reach the person.

1 Like

You never set detected to false.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.