Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

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

Asked by 7 years ago
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.)

0
I heard that you can't resume a yielded coroutine, but I am not sure. GatitosMansion 187 — 7y
1
You can't resume a dead coroutine, but you can resume a yeilded one. BlackJPI 2658 — 7y
0
Resuming a coroutine that yielded is the whole point of coroutines. Link150 1355 — 7y

1 answer

Log in to vote
0
Answered by
cabbler 1942 Moderation Voter
7 years ago

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

Answer this question