I want a function to restart if called again. The function is essentially built like this:
uis.InputBegan:Connect(function(input)
if input.KeyCode == Enum.KeyCode.Left then
print("do the thing")
task.wait(1)
print("do the other thing")
end
end)
Specifically, I am looking for a way to prevent the “other thing” from happening if the player hits the left arrow key during the second duration between the first “thing” and the “other thing.” I always want the original “thing” to happen upon pressing the key.
local busy = false
uis.InputBegan:Connect(function(input)
if input.KeyCode == Enum.KeyCode.Left and not busy then
busy = true
print("do the thing")
task.wait(1)
print("do the other thing")
busy = false
end
end)
Actually it looks like you want to do something slightly different: if the player presses the input again before 1 second has passed, “do the thing” again and do not do the previously queued “other thing” until another second has passed?
This is how it could be done without having to use coroutines but idk how efficient it is
local UIS = game:GetService("UserInputService")
local GlobalExecutionId = 0
UIS.InputBegan:Connect(function(input)
if input.KeyCode == Enum.KeyCode.Left then
GlobalExecutionId += 1 -- This will keep track of how many times this function has been called
local CurrentId = GlobalExecutionId -- Set the id for the current env
print("do the thing")
task.wait(1)
if GlobalExecutionId == CurrentId then -- Check GlobalExecutionId is the same, if it is continue, if not, stop.
print("do the other thing")
end
end
end)
local scheduledAction
local function onInputBegan(input: InputObject, gameProcessedEvent: boolean)
if gameProcessedEvent then
return
end
if input.KeyCode ~= Enum.KeyCode.Left then
return
end
if scheduledAction then
task.cancel(scheduledAction)
end
-- Initial stuff...
scheduledAction = task.delay(1, function()
-- Other stuff...
end)
end
UserInputService.InputBegan:Connect(onInputBegan)
I figured it out. This is pretty much the code I used.
doingthing = 0
uis.InputBegan:Connect(function(input)
if input.KeyCode == Enum.KeyCode.Left then
print("do the thing")
doingthing += 1
task.wait(1)
doingthing -= 1
if doingthing == 0 then
print("do the other other thing)
end
end
end)
A few people said similar stuff, but this is probably the simplest way to do it.