BoolValue prints both if statements

Hi,
I made a script when you press a true button it would make the bool value true and when you pressed on the false button it would make the bool value false. Then there’s the main button you press to print either true or false base on the if statement. Although when I pressed the true button first it printed correctly and then when I pressed the false button it printed both statements, so I’m confused? Is it suppose to do that?

uhhyea

True Local Script

local TrueEvent = game.ReplicatedStorage.RemoteEvent 
local BoolValue = game.ReplicatedStorage.BoolValue


script.Parent.MouseButton1Click:Connect(function()
	TrueEvent:FireServer()
end)

False Local Script

local FalseEvent = game.ReplicatedStorage.RemoteEvent2
local BoolValue = game.ReplicatedStorage.BoolValue



script.Parent.MouseButton1Click:Connect(function()
	FalseEvent:FireServer()
end)

Bool Server Handler

local TrueEvent = game.ReplicatedStorage.RemoteEvent 
local FalseEvent = game.ReplicatedStorage.RemoteEvent2


TrueEvent.OnServerEvent:Connect(function()
	game.ReplicatedStorage.BoolValue.Value = true
end)

FalseEvent.OnServerEvent:Connect(function()
	game.ReplicatedStorage.BoolValue.Value = false
end)

Main Local Script:

local BoolValue = game.ReplicatedStorage.BoolValue
local Button = script.Parent.Button

	
BoolValue:GetPropertyChangedSignal('Value'):Connect(function()
	if BoolValue.Value == true then
		Button.MouseButton1Click:Connect(function()
			print("true")
		end)
	else
		Button.MouseButton1Click:Connect(function()
			print("false")
		end)
	end
end)

I can see the issue by working through your main local script.

If the BoolValue is changed to true, the BoolValue:GetPropertyChangedSignal event is fired and the print(“true”) function is connected to the button.

If the BoolValue is then changed to false, the BoolValue:GetPropertyChangedSignal event is fired again and the print(“false”) function is connected to the button.

However the original print(“true”) function is not overwritten, and both functions are now connected to the button.

A way to fix this would be to keep track of the connection and disconnect any previous ones.

Main Local Script:

local BoolValue = game.ReplicatedStorage.BoolValue
local Button = script.Parent.Button

local currentConnection = nil

BoolValue:GetPropertyChangedSignal('Value'):Connect(function()
	if currentConnection ~= nil then
		currentConnection:Disconnect()
	end
	if BoolValue.Value == true then
		currentConnection = Button.MouseButton1Click:Connect(function()
			print("true")
		end)
	else
		currentConnection = Button.MouseButton1Click:Connect(function()
			print("false")
		end)
	end
end)
1 Like