How do I Make A TextButton Act As A Keybind

Hey, So im trying to make mobile support for my game. But, I cant figure out how do i make a text button act as a keybind.

I tried searching it on the forums, i couldnt find it. So, please help me.

local UserInputService = game:GetService("UserInputService")
local textButton = script.Parent

local keyCode = Enum.KeyCode.Space

local function simulateKeyPress()
    print("Keybind activated!")
    -- Add your keybind action here
end

textButton.MouseButton1Click:Connect(simulateKeyPress)

UserInputService.InputBegan:Connect(function(input, isProcessed)
    if not isProcessed then
        if input.KeyCode == keyCode then
            simulateKeyPress()
        end
    end
end)

You can replace Enum.KeyCode.Space with any key you want to use as the keybind, and add the action you want inside the simulateKeyPress function.

1 Like
local textButton = script.Parent
local userInputService = game:GetService("UserInputService")
local mobile = userInputService.TouchEnabled

-- Function to handle the button click
local function onButtonClick()
	textButton:Click()  -- Simulates a click on the TextButton
end

-- Connect the function to the button's MouseButton1Click event
textButton.MouseButton1Click:Connect(function()
	print("TextButton clicked!")  -- Replace this with your button's action
end)

-- Listen for key press events (for PC)
if not mobile then
	userInputService.InputBegan:Connect(function(input, gameProcessedEvent)
		if not gameProcessedEvent then
			if input.KeyCode == Enum.KeyCode.E then  -- Replace Enum.KeyCode.E with your desired key
				onButtonClick()
			end
		end
	end)
end

-- Handle touch input (for Mobile)
if mobile then
	-- Optionally, handle touch input here if needed, for example:
	textButton.TouchTap:Connect(function()
		onButtonClick()
	end)
end
1 Like

Ill try these codes later, thanks for writing this!

1 Like

If you’re looking for it to be compatible with the context action service, you’d bind the action like normal with the mobile button parameter as true,

e.g.

ContextActionService:BindAction("HonkHorn", handleAction, true, Enum.KeyCode.H, Enum.KeyCode.ButtonY)

then call ContextActionService:GetButton("HonkHorn") to get the button (or nil if it’s not mobile) and use that button as your mobile button.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.