Wootsoop
Wootsoop

Reputation: 13

Roblox studio how to detect key inputs?

I am trying to make a GUI that toggles on key input and i have already looked at the roblox wikipedia and a question that is supposedly what i am asking however it doesn't seem to work. Roblox Studio - Key Toggle for GUI

I have got no code because i completely don't understand ContextActionService so sorry.

Upvotes: 1

Views: 3870

Answers (1)

Kylaaa
Kylaaa

Reputation: 7188

In order to toggle a GUI on and off, you just need a reference to the UIElement and you can set its Parent value. ContextActionService:BindAction just allows you to bind the action to some kind of input.

Here's a simple example that is a little more explicit than the one in the linked question.

Make a LocalScript in StarterPlayer > StarterCharacterScipts, add this code

-- make a simple GUI to show off
local targetGui = Instance.new("ScreenGui")
local label = Instance.new("TextLabel", targetGui)
label.Text = "Hello World"
label.Position = UDim2.new(0, 0, 0, 0)
label.Size = UDim2.new(0, 200, 0, 30)

-- choose where to make the gui
local targetParent = game.Players.LocalPlayer.PlayerGui 

-- make a function for handling key presses
local function handleKeyPress(actionName, inputState, inputObj)
    -- DEBUG : show the information for this keypress
    print("Handle Key Press")
    print("Action Name : ", actionName)
    print("Input State : ", inputState)
    print("Input Obj - KeyCode : ", inputObj.KeyCode)
    print("")

    if inputState == Enum.UserInputState.End then
        if targetGui.Parent then
            targetGui.Parent = nil
        else
            targetGui.Parent = targetParent
        end
    end
end

-- connect that function to ContextActionService
local createDedicatedButtonOnMobile = false
game.ContextActionService:BindAction("toggleGui", handleKeyPress, createDedicatedButtonOnMobile, Enum.KeyCode.R)

Now whenever you press R it will parent or unparent the gui element. Now you've got a toggle.

BindAction is a very flexible function, so there isn't just one way to do this stuff. In this example, when you press R, you will see handleKeyPress fire a few times. Its output should look something like this :

Handle Key Press
Action Name : toggleGui
Input State : Enum.UserInputState.Begin
Input Obj - KeyCode :  Enum.KeyCode.R

Handle Key Press
Action Name : toggleGui
Input State : Enum.UserInputState.End
Input Obj - KeyCode :  Enum.KeyCode.R

This is because a key press has two states, one when you press the key down, and one when you lift the key up. The example function listens for when you lift up your finger before executing the toggle.

Hope this helps, let me know if you are still stuck.

Upvotes: 2

Related Questions