How do I fix this code?

It’s for a keybind GUI script. It “sorta” works, but not really. If I press G once, it will turn on. If I press G again, it won’t work. If I spam it, it has a 50/50 chance of turning off. Help?

local plr = game.Players.LocalPlayer

plr:GetMouse().KeyDown:Connect(function(Key)
 if Key == "g" then
  script.Parent.Visible = true	
	else
	script.Parent.Visible = false
end
end)
local plr = game.Players.LocalPlayer

plr:GetMouse().KeyDown:Connect(function(Key)
 if Key == "g" then
  script.Parent.Visible = not script.Parent.Visible
 end
end)

GetMouse() is considered Legacy, use UserInputService instead :wink:

It basically works the same thing if you’re using the InputBegan/InputEnded Events, except there’s 1 additional parameter on there which checks if the Input that was processed was from a CoreGui Input (PlayerList, Backpack, etc)

  • Parameter #1: The InputObject's Input
  • Parameter #2: A Bool checking if the Input was caused by the CoreGui
local UI = script.Parent
local Plr = game.Players.LocalPlayer
local UIS = game:GetService("UserInputService")
local Visible = false

UIS.InputBegan:Connect(function(Input, Chatted)
    if Chatted then -- This checks if it's been enabled by a CoreGui object
        return
    end

    if Input.KeyCode == Enum.KeyCode.G then
        UI.Visible = not UI.Visible
    end

end)