How bad would multiple threads aggravate performance?


I have a stamina script which runs some loops to pause regeneration however if you spam the sprint button multiple times, multiple threads spawn. The numbers in the output are the threads which print out the count below.

local UserInputService = game:GetService("UserInputService")
local RunService = game:GetService("RunService")

local Stamina = 100

local SprintHeld = false
local Sprinting = false
local Pausing = false
local Exhausted = false

local RunRefresh = 20 -- when to allow running after exhausted
local SpeedDiff = 6
local DrainRate = 2 -- drain per second
local RegenRate = 30
local PauseDelay = 3

local function GetCharacter()
	return game:GetService("Players").LocalPlayer.Character or game:GetService("Players").LocalPlayer.CharacterAdded:Wait()
end


local function sprint(active)
	local Character = GetCharacter()
	local Humanoid = Character:FindFirstChildOfClass('Humanoid')

	if Exhausted then return end -- we can't run because we're exhausted!
	
	Sprinting = active
	
	if active then
		Humanoid.WalkSpeed = Humanoid.WalkSpeed + SpeedDiff
		Pausing = false
	else
		Humanoid.WalkSpeed = Humanoid.WalkSpeed - SpeedDiff
		local Count = 0
		Pausing = true
		while Count < PauseDelay and not Sprinting and Pausing do 
			Count += 1
			task.wait(1)
			print(Count)
		end
		if Count >= PauseDelay then Pausing = false end
	end
end

UserInputService.InputBegan:Connect(function(input)
	if input.KeyCode ~= Enum.KeyCode.LeftShift or input.KeyCode == Enum.KeyCode.ButtonR2 then return end
	SprintHeld = true
	sprint(SprintHeld)
end)

UserInputService.InputEnded:Connect(function(input)
	if input.KeyCode ~= Enum.KeyCode.LeftShift or input.KeyCode == Enum.KeyCode.ButtonR2 then return end
	SprintHeld = false
	sprint(SprintHeld)
end)

RunService.Heartbeat:Connect(function(DeltaTime)
	if Sprinting then
		if Stamina > 0 then
			Stamina = Stamina - DrainRate * DeltaTime
		else
			sprint(false)
			Exhausted = true
		end
	elseif Stamina < 100 and not Pausing then
		Stamina = Stamina + RegenRate * DeltaTime
		if Stamina > RunRefresh then -- we can now run again!
			Exhausted = false
			if SprintHeld then -- resume running because player is still holding down the sprint key!
				sprint(SprintHeld)
			end
		end
	end
end)
1 Like

I’m just wondering if there are any work arounds to this.

1 Like

This is random: please use contextactionservice. If you hold shift while in chat you’ll lose stamina. You can also do:

if humanoid.MovingDirection.Magnitude </>0 then

So you don’t lose stamina whilst not moving.

Threads hurt performance, loops hurt performance even more, but not as much as threads with loops. You should research better ways of creating a sprint script. I would share mine, but I currently do not have access to the script.