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?
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.
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)