How can I make this while loop run whenever I am holding down a key and stop when I release a key?

Topic is pretty self-explanatory. This code doesn’t seem to print Running! whenever I press and hold the H key.

local UserInputService = game:GetService("UserInputService")

local Focused = false

UserInputService.InputBegan:Connect(function(input, gpe)
	if input.KeyCode == Enum.KeyCode.H and not gpe then
		Focused = true
		print(Focused)
	end
end)

UserInputService.InputEnded:Connect(function(input, gpe)
	if input.KeyCode == Enum.KeyCode.H and not gpe then
		Focused = false
		print(Focused)
	end
end)

while Focused do
	print("Runnin!")
	task.wait()
end

EDIT: I made a function that looks like this:

local function Run()
	while Focused do
		print("Runnin!")
		task.wait()
	end
end

at the beginning of my script after the Focused variable is declared and then call this function whenever one of the events fired and it worked. However, is there any other way that doesn’t use a function or is this the general way to achieve something like this?

3 Likes

You need to create a variable holding a bool and have the while loop run only when this bool is still true. When the key is first pressed you set the variable to true and on the release event you set the variable to false. This will stop the while loop.

1 Like

It’s as simple as this:

while true do
	if Focused then
		print("Runnin!")
	end
	task.wait() 
end
3 Likes

That is literally what my current not working code is doing.

1 Like

You could try using the UserInputService:IsKeyDown() function like so:

local UserInputService = game:GetService("UserInputService")

UserInputService.InputBegan:Connect(function(inputObject, gameProcessed)
    if gameProcessed then return end
    if inputObject.KeyCode == Enum.KeyCode.H then
        while UserInputService:IsKeyDown(Enum.KeyDown.H) do
            -- your code here
            task.wait()
        end
    end
end)
11 Likes

@NoParameters @NyrionDev Both of your solutions worked well, but I think @NoParameters solution is better and small. Thanks!

2 Likes