While loop not running

Here is the code:
image
It is not printing, why?
I expect it to loop print “Active!” while I am holding down click with the tool.

1 Like

You are starting active variable with “False”, that’s why while loop won’t run. You should start it with “True”

That just makes it run before I click, and it still doesn’t work after that

Also, keep in mind that whenever you change active variable to “False”, while loop will break for good

You should make somthing like this, so while loop won’t break:

while true do
     wait(0.1)
     if active then
          print("Active!")
     end
end
2 Likes

The code checks if active is true, which it is false by default. Then never checks again. This instead should work

local Activated = false

Tool.Activated:Connect(function()
	Activated = true
		
	local connection
	connection = Tool.Deactivated:Connect(function()
		Activated = false
		connection:Disconnect()
	end)
	
	while Activated do
		print("Active!")
		task.wait(.1)
	end
end)
3 Likes

Just noticed this loop will keep running even if the tool is unequipped or the character dies, which is probably unwanted.

local Tool = script.Parent
local Activated = false

Tool.Activated:Connect(function()
	Activated = true

	local connections = {}
	local function deactivate()
		Activated = false
		for i,v in pairs(connections) do
			v:Disconnect()
		end
        connections = nil
	end
	table.insert(connections, Tool.Deactivated:Connect(deactivate))
	table.insert(connections, Tool.Unequipped:Connect(deactivate))
	
	while Activated and Tool.Parent.Parent do
		print("Active!")
		task.wait(.1)
	end
end)
1 Like