On/off script not working

This script is supposed to print that the engines are on when you click y initially, but then when you click it again it prints that they are off. Yet when I keep pressing y it just prints that the engines are on.

	local function onInputBegan(input, gameProcessed)
		if input.KeyCode == Enum.KeyCode.Y then
			value.Value = true
			print("Fighter engines on")
			value2.Value = true

		end
	end
	
	local function onInputBegan2(input, gameProcessed)
		if input.KeyCode == Enum.KeyCode.Y then
			value.Value = false
			print("Fighter engines off")
			value2.Value = false

		end
	end

	
	if value2.Value == false then
		UserInputService.InputBegan:Connect(onInputBegan)

	end
	
	if value2.Value == true then
		UserInputService.InputBegan:Connect(onInputBegan2)

	end

Once connected it will stay connected. This code is also only ran once, as it is not ran upon every input. I would instead do something along these lines:

function toggleEngines(on) -- if on == true then engines are on, else off.
	value.Value = on
	print("Fighter engines:", on)
	value2.Value = on
end

UserInputService.InputBegan:Connect(function(input, processed)
	if input.KeyCode == Enum.KeyCode.Y then
		toggleEngines(not value2.Value) -- Invert current value (if they are on, then they will turn off)
	end
end)

You could also split the toggleEngines(on) function into turnOn() and turnOff() if you need to do different things depending on if they start or stop.

1 Like