Mana Regen Cooldown Inconsistencies

Hella Fellas,

I’m trying to make mana a resource you can’t spam. Regeneration should stop for a couple seconds after mana has been used, but it only does that on rare occasions.

Instead, it will cool down the regeneration if it was last at 100. But if the mana is in the middle of regenerating, the regeneration will not stop if its used again.

Attempt 1 (Mega Loop)
local rs = game:GetService("RunService")
local mana = script.Parent
local plr = game.Players:FindFirstChild(mana.Parent.Name)

local regen = false
local wTime = 2
local mRate = 8

rs.Heartbeat:Connect(function(del)
	local char = workspace:FindFirstChild(plr.Name)
	if mana.Value > 100 then
		mana.Value = 100
	elseif mana.Value <= 0 then
		mana.Value = 1
		if char then
			char.Humanoid:TakeDamage(5)
		end
	elseif mana.Value < 100 then
		coroutine.wrap(function()
			local lV = mana.Value
			for i=1, wTime*60 do
				rs.Heartbeat:Wait()
				if lV > mana.Value or mana.Value >= 100 then
					coroutine.yield()
				end
			end
			if lV <= mana.Value and mana.Value < 100 then
				--print(lV)
				mana.Value = mana.Value + del*mRate
			end
			coroutine.yield()
		end)()
	end
	rs.Heartbeat:Wait()
end)
Attempt 2 (Event + Loop)
--scripted by GreekForge
local rs = game:GetService("RunService")
local mana = script.Parent
local plr = game.Players:FindFirstChild(mana.Parent.Name)

local regen = true
local wTime = 2
local mRate = 8

mana.Changed:Connect(function()
	local char = workspace:FindFirstChild(plr.Name)
	if mana.Value > 100 then
		mana.Value = 100
		regen = false
	elseif mana.Value < 0 then
		mana.Value = 1
		if char then
			char.Humanoid:TakeDamage(5)
		end
		regen = true
	else
		regen = true
	end
end)

while true do
	rs.Heartbeat:Wait()
	if regen then
		local lV = mana.Value
		wait(wTime)
		if lV <= mana.Value then
			while true do
				local dt = wait()
				mana.Value = mana.Value + dt*mRate
				lV = mana.Value
				rs.Heartbeat:Wait()
				if lV > mana.Value then
					break
				end
			end
		end
	end
end

I don’t get why it won’t stop during regeneration. I was thinking it might have something to do with coroutines and how the threading worked, but…

1 Like