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

Making an oxygen script with coroutines, anyone know why this isnt working?

char = game.Players.LocalPlayer.Character
hum = char.Humanoid

o = Instance.new('IntValue')
o.Name = "oxygen"
o.Parent = char
o.Value = 100

deplete = coroutine.create(function()
	while o.Value > 0 do
		wait(.5)
		o.Value = o.Value - 5	
	end
end)

restore = coroutine.create(function()
	while o.Value < 100 do
		wait(.5)
		o.Value = o.Value + 5
	end
end)

hum.StateChanged:connect(function(old,new)
	if new == Enum.HumanoidStateType.Swimming then
		print "im swimming"
		b = game.Lighting.Bubbles:Clone()
		b.Parent = char.Head
		if coroutine.status(restore) == "running" then
			coroutine.yield(restore)
			coroutine.resume(deplete)
		elseif coroutine.status(restore) ~= "running" then
			coroutine.resume(deplete)	
		end
	end
end)

hum.StateChanged:connect(function(old,new)
	if old == Enum.HumanoidStateType.Swimming then
		print "now im not"
		coroutine.yield(deplete)
		coroutine.resume(restore)
		if char.Head:FindFirstChild('Bubbles') then
			char.Head.Bubbles:Destroy()
		else
			print "well."
		end
	end
end)

It works in the water until I jump or get out, at which point both coroutines activate and the oxygen value flickers between two numbers. Anyone know why?

(This is my first time working with coroutines, if anyone has any tips or advice I'd appreciate it.)

3 comments

0

I heard that you can't resume a yielded coroutine, but I am not sure.

1

You can't resume a dead coroutine, but you can resume a yeilded one.

0

Resuming a coroutine that yielded is the whole point of coroutines.

1 answer

✓ Accepted answer

I don't see a reason to have a complicated coroutine setup here. Have a variable called oxygenAdd which is either 1 or -1.

while wait(0.5) do
	o.Value = o.Value + oxygenAdd * 5
end

Anyway the major issue here is you connected hum.StateChanged to two different functions. Just do this.

hum.StateChanged:connect(function(old,new)
	local swim = Enum.HumanoidStateType.Swimming
	if swim == new then
        	print "im swimming"
        elseif swim == old then
		print "now im not"
	end
end)

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