Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

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

Asked by 2 years ago

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

Log in to vote
0
Answered by
Miniller 562 Moderation Voter
2 years ago

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

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. User#47934 5 — 2y
Ad
Log in to vote
0
Answered by 2 years ago

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

Answer this question