How do I make it so this code doesnt work when a GUI Element isnt visible?

Hello, im trying to make it so when a player pressed C when a GUI element is visible it does something, but when the GUI element isnt visible, players are still able to press C to make that something appear. Here is the code:

local Enabled = false
local UIS = game:GetService("UserInputService")

UIS.InputBegan:Connect(function(input, gameProcessedEvent)
    if input.KeyCode == Enum.KeyCode.C then
        if not Enabled then
            Enabled = true
            game.Players.LocalPlayer.Backpack.Camera1.Disabled = false
            game.Players.LocalPlayer.PlayerGui.camgui.CamButtons.Visible = true
            game.Workspace.CameraDummy1.Transparency = 1
        else
            Enabled = false
            game.Players.LocalPlayer.PlayerGui.camgui.CamButtons.Visible = false
            workspace.CurrentCamera.CameraType = Enum.CameraType.Custom
            game.Players.LocalPlayer.Backpack.Camera2.Disabled = true
            game.Players.LocalPlayer.Backpack.Camera1.Disabled = true
            game.Players.LocalPlayer.Backpack.Camera3.Disabled = true
        end
    end
end)

Ive tried putting it in an

Ive tried putting it in an if

game.Players.LocalPlayer.PlayerGui.camgui.maincambutt.Visible = true

then but it didnt work, i also added an

else if game.Players.LocalPlayer.PlayerGui.camgui.maincambutt.Visible = false

and it didnt work. To clarify, im trying to make it so when a GUI element is visible on a screen a KeyCode will work, and when its not visible the KeyCode wont work.

Im also doing this in a Local Script.

1 Like

Maybe add a WaitForChild like this?

game.Players.LocalPlayer:WaitForChild("PlayerGui"):WaitForChild("camgui").CamButtons.Visible = true

That is very dangerous and bad practice.

Instead just turn them into variables:

local Players = game:GetService("Players")
local playergui = Players.LocalPlayer:WaitForChild("PlayerGui")
local camgui = playergui:WaitForChild("camgui")

camgui.CamButtons.Visible = true

Way more clean and way more safe than having a chain of WaitForChilds.

1 Like

if script.Parent.Visible == true then

if game.Players.LocalPlayer.PlayerGui.camgui.maincambutt.Visible = true
then
       scriptpath.Disabled = false
else
      scriptpath.Disabled = true
end
2 Likes