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

How to detect if player is holding down a GUI button?

So my script works as usual but only when it is clicked. I want it to do it only when it is held. Code:

script.Parent.MouseButton1Down:Connect(function()
	local player = game.Players.LocalPlayer
	player.Character:PivotTo(player.Character:GetPivot() * CFrame.new(0, 0, 0.01))
end)

I thought of doing a loop but I don't know when it is no longer held. Any help?

2 answers

✓ Accepted answer

You can use coroutines for this. It works, although for some reason it spams the console with an error no matter what safety checks I implement.

local thread
script.Parent.MouseButton1Down:Connect(function()
	thread = coroutine.create(function()
		wait(2)
		print("been holding for 2 seconds")
	end)
	coroutine.resume(thread)
end)

script.Parent.MouseButton1Up:Connect(function()
	coroutine.close(thread)
end)

Whenever you first press it, it spawns a new thread, which will wait for 2 seconds. In the MouseButton1Up event, we kill that thread, therefore we can be sure that if the thread's still running after 2 seconds, a player was holding it that long.

Some people might recommend you use wait, however, it's probably not a good idea.

Learn more about coroutine

1 comment

0

But I want to loop 'player.Character:PivotTo(player.Character:GetPivot() * CFrame.new(0, 0, 0.01))' until it is no longer held. Sorry for misunderstanding.

I fixed the problem. The custom character had something anchored and i decided to unanchor it.

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