luaroblox

How to implement a Key Toggle for GUI instead of mouse click in Roblox


I have a Frame GUI, I want to make it where when a player has the GUI when they're running the game, that they can press a certain key to toggle it (ON) and (OFF). So an Open/Close System. Instead of using a Mouse Click I want a key toggle. Any idea on how to do this?


Solution

  • http://wiki.roblox.com/index.php?title=Keyboard_input This link explains 2 ways, the better way is the top or here:

    local toggle = false -- false is Off; true is On
    
    
    function onKeyPress(actionName, userInputState, inputObject)
        if userInputState == Enum.UserInputState.Begin then
            print("R was pressed")
            if toggle == false then
                 toggle = true
                  -- INSERT Making GUI Visible
            else
                toggle = false
                -- INSERT making GUI Invisible
            end
        end
    end
    
    game.ContextActionService:BindAction("keyPress", onKeyPress, false, Enum.KeyCode.R)
    

    -- The above line could also been written as:
    -- game.ContextActionService:BindAction("keyPress", onKeyPress, false, "r")