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.)
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)