So, I have a running script, and I'm curious how I would have it go until the player has been holding the timer for fifteen seconds.
Would I use a wait or what?
Here's the script (LocalScript)
--Setup variables local running = false game:GetService("UserInputService").InputBegan:Connect(function(inputObject, gameProcessedEvent) if inputObject.KeyCode == Enum.KeyCode.LeftShift then running = true game:GetService("UserInputService").InputEnded:Connect(function(inputObject, gameProcessedEvent) if inputObject.KeyCode == Enum.KeyCode.LeftShift and running then running = false end end) end end)
You shouldn't connect to an event multiple times without reason. Consider this script instead:
--Setup variables local running = false game:GetService("UserInputService").InputBegan:Connect(function(inputObject, gameProcessedEvent) if inputObject.KeyCode == Enum.KeyCode.LeftShift then running = true end end) game:GetService("UserInputService").InputEnded:Connect(function(inputObject, gameProcessedEvent) if inputObject.KeyCode == Enum.KeyCode.LeftShift and running then running = false end end)
If you wanted to use a wait
, you would set it up like this:
--Setup variables local running = false local runLimit = 15 -- in seconds local runInstance = 0 game:GetService("UserInputService").InputBegan:Connect(function(inputObject, gameProcessedEvent) if inputObject.KeyCode == Enum.KeyCode.LeftShift then running = true -- Make sure that if the player starts running again, this thread won't do anything runInstance = runInstance + 1 local instance = runInstance wait(runLimit) if running and runInstance == instance then running = false end -- else the player has either stopped running OR stopped & resumed, meaning there's a new 'wait(runLimit)' running, meaning we shouldn't do anything end end) game:GetService("UserInputService").InputEnded:Connect(function(inputObject, gameProcessedEvent) if inputObject.KeyCode == Enum.KeyCode.LeftShift and running then running = false end end)
Of course, this simply means that a player need only release 'shift' for a moment to continue running. If you wanted stamina, you have two choices:
runInstance ~= instance or not running
, in which case break the loop. If stamina runs out, stop running and then increase the stamina after every second until runInstance ~= instance or running
or until you hit the maximum stamina.Another note: you should probably have functions for "StartRunning" and "StopRunning"; these can change the running
variable and also keep the player's Humanoid's speed up-to-date.