While loop still running even though bool is set to false

Does anyone know why this code doesn’t work?

local Tool = script.Parent
local RemoteEvent = Tool:WaitForChild("RemoteEvent")

-- Client

Tool.Activated:Connect(function()
	RemoteEvent:FireServer(true)
end)

Tool.Deactivated:Connect(function()
	RemoteEvent:FireServer(false)
end)

-- Server

RemoteEvent.OnServerEvent:Connect(function(player, isActive)
	while isActive do
		print("Active")
		wait(0.1)
	end
	-- runs loop again even though isActive is set to false
end)
2 Likes

This would be because the isActive that was sent through the remote event is what is being checked, as Firing a event does not update the last time the event was fired unless it is a variable outside of the function that is being changed.

It’s because if just keeps creating new while true loops every remote event. You’ll need to separate the while true from the remote event somehow.

do this for your server

local active
RemoteEvent.OnServerEvent:Connect(function(player, isActive)
	active=isActive
end)
while active do
	print("Active")
	wait(0.1)
end

you might wanna wrap that while loop in a spawn() or maybe coroutine