Set bind ONLY if GUI is visible

Hello, I have a settinggui that is supposed to set a keybind. First, you must open up the gui, and click the parent of the script (a button). The only problem is the script is still setting the keybind even after it finished asking the player for a keybind.

local UIS = game:GetService("UserInputService")
local canChange = false
script.Parent.MouseButton1Click:Connect(function()
	script.Parent.Parent.Parent.Popup.Visible = true
	UIS.InputBegan:Connect(function(input, gpe)
		if canChange then
			if input.UserInputType == Enum.UserInputType.Keyboard then
				script.Parent.Text = tostring(input.KeyCode)
			elseif input.UserInputType ~= Enum.UserInputType.MouseMovement or Enum.UserInputType.MouseWheel then
				script.Parent.Text = tostring(input.UserInputType)
			end
		end
		script.Parent.Parent.Parent.Popup.Visible = false
		canChange = false
	end)
end)

if script.Parent.Parent.Parent.Popup.Visible then
	canChange = true
end

Not sure if this might help, but this is the structure of the GUIs
image

The popup that should allow the player to change the keybind is named ‘Popup’ in this structure.

How can I solve my issue?

i mean the title says it all just do an if statement that checks if the gui is visible or not.

i edited it, should i do:

local UIS = game:GetService("UserInputService")
script.Parent.MouseButton1Click:Connect(function()
	script.Parent.Parent.Parent.Popup.Visible = true
	UIS.InputBegan:Connect(function(input, gpe)
		if script.Parent.Parent.Parent.Popup.Visible then
			if input.UserInputType == Enum.UserInputType.Keyboard then
				script.Parent.Text = tostring(input.KeyCode)
			elseif input.UserInputType ~= Enum.UserInputType.MouseMovement or Enum.UserInputType.MouseWheel then
				script.Parent.Text = tostring(input.UserInputType)
			end
		end
		script.Parent.Parent.Parent.Popup.Visible = false
	end)
end)

Edit: This script also did not work.

Weird, maybe try making an boolValue and setting it to true whenever the gui is truned on???

Isn’t that essentially what I did in the OG post?

I meant a boolValue object, you could give it a try because i cannot see any way else than using an if statement.

Other than that id like to ask how you turned the GUI off.

the popup or the settingmenu itself?

Yikes, more instructions than i simple variable, ain’t it?

I have just realized that theres this line of code.

Im pretty sure the problem here is that this doesnt work because if it only checks the visible bool at the first frame once.

are you implying i should add a while loop?

It would be less optimized, but yeah thats a way.
i recommend using if and else statements that change a variable inside the MouseButton1Up event.