Coroutine starts when value is true but does not yield when it's false

I’m making an NPC constantly look at the player when they’re in range and in view by using a value and a coroutine. The problem is that even though the value is set to false, the coroutine continues on. Why?

--Local script in StarterCharacterScripts simplified:

if dotProduct > .5 and npcToCharacterDistance < 30 then
			--in FOV
			print("Player in Field Of View! Firing event...")
			event:FireServer(npc, true)
else
			event:FireServer(npc, false)
end

Script in enemy:

local rs = game:GetService("ReplicatedStorage")
local events = rs:WaitForChild("CombatEvents")
local vision = events:WaitForChild("VisionEvent")
local enemyHandler = require(events:WaitForChild("EnemyModule"))

vision.OnServerEvent:Connect(function(plr, npc, value)
	if value == true then
		print(plr, "triggered vision on", npc)
		enemyHandler.lookAt(npc, plr, true)
	else
		print(plr, "has disappeared on", npc)
		enemyHandler.lookAt(npc, plr, false)
	end
end)

Module script in ReplicatedStorage:

local enemy = {}

local function task(value, target, enemyNPC)
	while value == true do
		warn(value)
		wait(.5)
		local character = game.Workspace:FindFirstChild(target.Name)
		local npcToCharacterDistance = (enemyNPC.HumanoidRootPart.Position - character.HumanoidRootPart.Position).magnitude
		--warn("-----------", npcToCharacterDistance, "-----------")
		if npcToCharacterDistance < 30 and value == true then
			enemyNPC.HumanoidRootPart.CFrame = CFrame.lookAt(enemyNPC.HumanoidRootPart.Position, character.HumanoidRootPart.Position)
		end	
	end
end

local taskCoro = coroutine.create(task)

function enemy.lookAt(enemy, target, value)
	warn(enemy, target, value)
	
	if value == true then
		local success, result = coroutine.resume(taskCoro, value, target, enemy)
		print(success, result)
	else
		local success, result = coroutine.yield(taskCoro)
		print(success, result)
	end
	
end

return enemy

Output when the value gets changed to false:

bruceywayne has disappeared on Thug - Server - AI:11
15:53:30.329 Thug bruceywayne false - Server - EnemyModule:19
15:53:30.592 :arrow_forward: true (x9) - Server - EnemyModule:5

I’m new when it comes to coroutines, I tried making this using the documentation.

1 Like