Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How to keep a gui projected when player holds down a button?

I managed to make something that displays a gui for three seconds when the player clicks the "P" button on the keyboard.

function onKeyPress(viewMoney, userInputState, inputObject)
	if userInputState == Enum.UserInputState.Begin then
		local money = script.Parent.Data.MoneyVal.Value
		script.Parent.Money.Text = "$"..money
		script.Parent.Visible = true
		wait(3)
		script.Parent.Visible = false
	end
end

game.ContextActionService:BindAction("keyPress", onKeyPress, false, Enum.KeyCode.P)

I am wondering how I could make it so that the gui will stay displayed the entire time the P button is being held down plus three additional seconds when they let go. Thanks.

1 answer

✓ Accepted answer

The answer to this is more easily done with UserInputService. UserInputService has two very useful events; InputBegan and InputEnded. Their names are pretty self explanatory.


Here is some code I have written for you, it may be of use.

local keyToHold = Enum.KeyCode.P

local uis = game:service("UserInputService")
local frame = script.Parent
local money = frame:WaitForChild("Data"):WaitForChild("Money") --// WaitForChild lets the child load instead of trying to index things that may not have loaded
local text = frame:WaitForChild("Money")
--// I define these variables right at the start so that I do not have to repeatedly index things, I can just do it now!

function toggleVisibility(bool)
	if bool == true then
		text.Text = "$" ..money.Value
	elseif bool == false then
		wait(3)
	end
	frame.Visible = bool
end

uis.InputBegan:connect(function(key,gp) --// 'key' = InputObject, 'gp' = GameProcessedEvent (whether a player is typing or not)
	if gp == false and key.KeyCode  == keyToHold then
		toggleVisibility(true)
	end
end)

uis.InputEnded:connect(function(key,gp)
	if gp == false and key.KeyCode == keyToHold then
		toggleVisibility(false)
	end
end)

Do you need more explanation? You seem to understand how things work, so I don't think I need to explain the basics.


Hope I helped!

~TDP

This discussion is preserved as it was. New answers, comments, and votes are closed.