Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Why does this coroutine fail to work correctly?

EDIT: Resolved by legokendall

For some reason, the "for i=1,#cooldown do" part doesn't work. However, everything else works. Any idea why? Also note that I've tried printing out plr, stat, and cooldown in function Cooldown(), and they all gave me the correct results.

wait()
function Cooldown(plr)
local stat = game.ServerStorage.PlayerStats2:FindFirstChild(plr.Name):WaitForChild("SummonCooldown")
local cooldown = stat.Value
for i=1,#cooldown do
wait(1)
stat.Value = stat.Value - 1
end end

function game.ReplicatedStorage.CheckSummonCooldown.OnServerInvoke(plr,cooldown)
local stat = game.ServerStorage.PlayerStats2:FindFirstChild(plr.Name):WaitForChild("SummonCooldown")
if stat.Value == 0 then
stat.Value = cooldown
coro = coroutine.create(Cooldown)
coroutine.resume(coro,plr)
return 0
else
return stat.Value
end end

2 answers

✓ Accepted answer

The hastag on line 5 is not necessary due to "cooldown" already being a number :)

wait()
function Cooldown(plr)
local stat = game.ServerStorage.PlayerStats2:FindFirstChild(plr.Name):WaitForChild("SummonCooldown")
local cooldown = stat
for i=1,cooldown.Value do
wait(1)
stat.Value = stat.Value - 1
end end

function game.ReplicatedStorage.CheckSummonCooldown.OnServerInvoke(plr,cooldown)
local stat = game.ServerStorage.PlayerStats2:FindFirstChild(plr.Name):WaitForChild("SummonCooldown")
if stat.Value == 0 then
stat.Value = cooldown
coro = coroutine.create(Cooldown)
coroutine.resume(coro,plr)
return 0
else
return stat.Value
end end

If you aren't using coroutine.yield in your code, you don't really have any business using the coroutine library.

Use spawn(f) if you want to start a new function "in the background". It plays more nicely with wait.

There's not a good reason for the for loop in the first place. Just wait(stat.Value) stat.Value = 0 accomplishes the same thing, but is much simpler.

In that case, you might as well just use a delay.


Instead of using :FindFirstChild(plr.Name) just use [plr.Name].


wait()

function game.ReplicatedStorage.CheckSummonCooldown.OnServerInvoke(plr,cooldown)
	local stat = game.ServerStorage.PlayerStats2[plr.Name]:WaitForChild("SummonCooldown")
	if stat.Value == 0 then
		stat.Value = cooldown
		delay(cooldown, function()
			stat.Value = 0
		end)
		return 0
	else
		return stat.Value
	end
end

and at that point SummonCooldown might as well be a BoolValue.

This discussion is preserved as it was. New answers, comments, and votes are closed.