Why does declaring a variable break UserInputSerice

I was messing with UserInputService as a test, and when I tried to declare a variable which is equal to a TextButton, it doesn’t work.

This code does work, it has no variables equal to a Gui, it just says it in the if statement:

local userInputService = game:GetService("UserInputService")

userInputService.InputBegan:Connect(function(input, gameProcessedEvent)

	if input.UserInputType == Enum.UserInputType.Keyboard then 
		if input.KeyCode == Enum.KeyCode.Q then
			script.Parent.ScreenGui.TextButton.Visible=true
			print("You pressed Q") 
			wait(1)
			script.Parent.ScreenGui.TextButton.Visible=false
			print(gameProcessedEvent)
		end
	end
end)

This is why I’m posting, this will not work:

local userInputService = game:GetService("UserInputService")
local buttonVisibility = script.Parent.ScreenGui.TextButton.Visible

userInputService.InputBegan:Connect(function(input, gameProcessedEvent)

	if input.UserInputType == Enum.UserInputType.Keyboard then 
		if input.KeyCode == Enum.KeyCode.Q then
		    buttonVisibility=true
			print("You pressed Q") 
			wait(1)
			buttonVisibility=false
			print(gameProcessedEvent)
		end
	end
end)

Why is it that when I declare a variable, nothing works (Not even the print statement worked), but when I just say it, with no variables, it works prints what I want it to print, and makes the Gui visible, then one second laters its invisible again, just how I want it!

Code runs from top-to-bottom. So most likely, there is an issue with the variable itself.

Try using the debugger to track the code step-by-step to see the issue. buttonVisibility may be nil and throw an error.

1 Like

This stores the property’s value, not a reference to the property

2 Likes

Maybe try button.Visible instead of using it in the variable.

When you do local buttonVisibility = script.Parent.ScreenGui.TextButton.Visible, it only reads the value. So, in your example, the variable gets set to a simple boolean (false). For example, if I read the value of a BoolValue, like so…

local Val = workspace.BoolVal.Value

Val would be false. If I changed Val, it would only change the variable.
Now, here’s the workaround. If you index the TextButton but not the value of it like so:

local Button = script.Parent.ScreenGui.TextButton

Then I can change the button freely like so using your example:

local Button = script.Parent.ScreenGui.TextButton

userInputService.InputBegan:Connect(function(input, gameProcessedEvent)
	if input.UserInputType == Enum.UserInputType.Keyboard then 
		if input.KeyCode == Enum.KeyCode.Q then
		    Button.Visible = true
			print("You pressed Q") 
			wait(1)
			Button.Visible = false
			print(gameProcessedEvent)
		end
	end
end)

When you do this, it references the Instance in the variable, rather than a boolean, allowing you to change the button’s properties.