Conditional Events Not Working - Help please

  • I am trying to maintain the state of a bridge in my script (bridgeState). I have set up two functions, one to Activate the bridge (activateBridge()) and another de-activate it (deactivateBridge()).

  • The default script settings have the bridgeState set to “false”

  • When I touch the Part (button) the conditional print statement runs, and the bridge activates. In addition, the bridgeState changes to true

  • When I touch the button again, nothing happens. It simply fires the Activate() bridge function again.

    • Can someone help explain to me why the conditional expression is not re-evaluated once the state changes?
local button = script.Parent
local bridge = game.Workspace.Bridge

button.Anchored = true
button.BrickColor = BrickColor.new("Bright green")

local bridgeState = false

local function activateBridge()
	print("Button is now active!")
	button.BrickColor = BrickColor.new("Really red")
	bridge.Transparency = 0
	bridge.CanCollide = true
	bridgeState = true 
end

local function deactivateBridge()
	print("Bridge is now off!")
	button.BrickColor = BrickColor.new("Bright green")
	bridge.Transparency = .5
	bridge.CanCollide = false
	bridgeState = false
end

if bridgeState == false then
	button.Touched:Connect(activateBridge)
	print("Player pressed the button! bridgeState is now " .. tostring(bridgeState))
end

if bridgeState == true then
	button.Touched:Connect(deactivateBridge())
	print("Player pressed to turn off.  bridgeState is now " .. tostring(bridgeState))
end

You should try doing this instead of the two if statements.

button.Touched:Connect(function()
     if bridgeState then  -- If bridgeState is true then...
          deactivateBridge()
     else -- If bridgeState is false then...
          activateBridge()
end)
1 Like

@ComplicatedParadigm Thanks! That does fix the issue! Can you explain why my previous version didn’t work?

It didn’t work because the script only runs once, to completion. So bridgeState is false, and the activateBridge function would be bound, and that’s it; it never rebinds to a different function.

The solution is moving the checks within the touch function itself, which will always run, and the flag changes so the function is dynamic.

1 Like

@Darkmist101 Thank you so much.