How can I make a toggle button with one button?

So I am making a siren control panel and I want the “WAIL” button to be a toggle button. After the first click, the lights and sirens start playing. After the second click, it all stops. If they press it once again, it starts playing the lights and sirens once again. It’s like a loop.

The problem is that I can’t figure out how. I tried making if statements and adding BoolValues to check if it’s on but it’s just not working. What I mean is that once it’s clicked and the BoolValue (“on”) changes to true, the script automatically continues to shut it off because it’s “on”.

Here is the script:

local wail = workspace["A-Chassis Suspension 3500HD"].DriveSeat.Wail
local lights = workspace["A-Chassis Suspension 3500HD"].Body.LIGHTBAR.Lights
local db = false
local on = workspace["A-Chassis Suspension 3500HD"]["A-Chassis Tune"].InitiateSirenControl.SirenControl.Frame.Sirens.Wail.On
local children = lights:GetChildren()
local running = false

local function stopRunning()
	running = false
end

script.Parent.MouseButton1Click:Connect(function()
	if db == false then
		db = true
		if on.Value == false then
			on.Value = true
			wail:Play()
			running = true
			wail.Playing = true or wail:Play()
			spawn(function()
				while task.wait(0.2) and running == true do
					for _ = 1, 3 do
						task.spawn(function() 
							local light = children[math.random(#children)]

							if (not light:IsA("BasePart")) then 
								print("Not light")
								return;
							end

							light.Transparency = 0
							task.wait(0.1)
							light.Transparency = 1
							db = false
						end)
						if running == false then
							print("STOPPING!")
							continue
						end
					end
				end
			end)
		end
	end


	if wail.Playing == true then
		repeat wait() until running == false
		stopRunning()
		wail:Stop()
		print("Stopped")
		return
	end
end)

Does anybody have any suggestions or ideas? Much appreciated!

Try having a variable that you change depending on if its on or off, and use if-else to check

Just do

script.Parent.MouseButton1Click:Connect(function()
      if db == false then
            --turn on siren code
      elseif db == true then
            --turn off siren code
      end
end)
1 Like

The method that I most commonly use is keeping a variable such as, ‘isToggled’, and making sure to disable/enable it whenever the requested event fires.

local isToggled = (false);
function Toggle()
   isToggled = not isToggled
   if (isToggled) then
       -- Is toggled.
  else
       -- Isn't toggled.
   end;
end;

-- Whatever connection
1 Like

Thats the problem. If they turn on the siren and the variable changes to “on”, the script checks if its “on” and automatically turns the siren off after the first click.

No, Check the value when clicking and only when you click it. This should prevent it automatically turning off