✓ Accepted answer
You shouldn't connect to an event multiple times without reason. Consider this script instead:
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:
local running = false
local runLimit = 15
local runInstance = 0
game:GetService("UserInputService").InputBegan:Connect(function(inputObject, gameProcessedEvent)
if inputObject.KeyCode == Enum.KeyCode.LeftShift then
running = true
runInstance = runInstance + 1
local instance = runInstance
wait(runLimit)
if running and runInstance == instance then
running = false
end
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:
- (Easy) Decrease stamina every second unless
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.
- (Harder) Decrease stamina based on the time spent running.
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.
1 comment
Your code will add a new InputEnded event each time the code is ran.