How do I check if a key is being held and released?

Hello,

I would like to make a loop where on the right mouse click button, an event constantly fires and when the right mouse click button is released, it stops.

Are there any specific functions I can use for this? This didn’t seem to work.

local UserInputService = game:GetService("UserInputService");

local Held = false;
UserInputService.InputBegan:Connect(function(Input)
    if Input.UserInputType == Enum.UserInputType.MouseButton2 then
        Held = true;
    end
end)

local Func = coroutine.create(function()
    while Held == true do
        wait();
        print("Works!");
    end
end)

coroutine.resume(Func);
3 Likes

You can do this in combination with InputEnded so you can detect when the key is released.

local UserInputService = game:GetService("UserInputService");

local Held = false;
UserInputService.InputBegan:Connect(function(Input)
    if Input.UserInputType == Enum.UserInputType.MouseButton2 then
        Held = true;
    end
end)

UserInputService.InputEnded:Connect(function(Input)
    if Input.UserInputType == Enum.UserInputType.MouseButton2 then
        Held = false;
    end
end)

local Func = coroutine.create(function()
    while Held == true do
        wait();
        print("Works!");
    end
end)

coroutine.resume(Func);
2 Likes

There’s on issue,

The printing only starts when I release the rightmouseclick. Do you know how to fix this?

You could try this:

local UserInputService = game:GetService("UserInputService");

local Held = false;

local Func = coroutine.create(function()
    while Held == true do
        wait();
        print("Works!");
    end
end)

UserInputService.InputBegan:Connect(function(Input)
    if Input.UserInputType == Enum.UserInputType.MouseButton2 then
        coroutine.resume(Func)
        Held = true;
    end
end)

UserInputService.InputEnded:Connect(function(Input)
    if Input.UserInputType == Enum.UserInputType.MouseButton2 then
        Held = false;
    end
end)

coroutine.resume(Func);

So that way it’ll keep printing until the InputEnded Event detects the change

2 Likes

this deos not work are you sure you need those semi colons