How can I bind a function to a GUI button?

Hello, I have an existing text button, and I want to make it so when the player touches the button, the same function that executes when the player touches a determined key happens.

An example would be =

UIS.InputBegan:Connect(function(input,isTyping)
if isTyping then return end

if input.KeyCode == Enum.KeyCode.G then

print(“test”)

end)

I would want to make it so when a player touches a text button, the same function is executed. I want to make this to add mobile support to my game.

I don’t know how to do it. I have tried looking up posts and videos but I didnt get to understand them, so can anybody please help?

local userInputService = game:GetService("UserInputService")

-- this function will be called when i press the G key or if i click the button
local function MyCoolFunction()
	print("Hi i'm cool")
end

userInputService.InputBegan:Connect(function(input, processed)
	-- if the input was processed then exit the function early and do nothing
	if processed == true then return end
	-- if the input was not a keyboard then exit the function early and do nothing
	if input.UserInputType ~= Enum.UserInputType.Keyboard then return end
	-- if the input was not key G then exit the function early and do nothing
	if input.KeyCode ~= Enum.KeyCode.G then return end
	-- call my cool function
	MyCoolFunction()
end)

-- if someone presses the button call my cool function
script.Parent.Button.Activated:Connect(MyCoolFunction)
2 Likes