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

While loops doing what they need to multiple times?

Asked by 2 years ago

In my game, I am working on adding a Poison status effect, I have two while loops doing two different things; one is counting down the venom value when it is more than 0, and the other is removing the player's health as long as the value is above 0. The problem is, the loops start doing their function multiple times. For example, the while loop that is supposed to be counting the venom value down while it is above 0 will work fine for the first loop, but then the loop starts stalking on top of itself, and won't even stop when it is at 0. Instead, it counts down like this: 10, 9, 7, 3, -5, and then stops at -5. I have no idea why this is happening, help would be appreciated.

01char.charactervalues.Venom.Changed:Connect(function()
02    if char.charactervalues.Venom.Value > 0 then
03        char.Torso.Poison.Enabled = true
04        while char.charactervalues.Venom.Value ~= 0 do
05            char.Humanoid.Health -= 3
06            wait(0.8)
07        end
08    else
09        char.Torso.Poison.Enabled = false
10    end
11end)
12 
13char.charactervalues.Venom.Changed:Connect(function()
14    if char.charactervalues.Venom.Value > 0 then
15        while char.charactervalues.Venom.Value ~= 0 do
16            wait(1)
17            char.charactervalues.Venom.Value -= 1
18        end
19    end
20end)

1 answer

Log in to vote
1
Answered by 2 years ago

The way :Connect() functions work, is that each time the event triggers (in this case, the venom value), it starts a new function running the code. So, when your while loop is running, it is changing the venom value, and stacking new loops on top, causing it to behave very weirdly. A simple fix for this is a debounce value. Changed code:

01debounce = false
02 
03char.charactervalues.Venom.Changed:Connect(function()
04    if debounce == false then
05        debounce = true
06        if char.charactervalues.Venom.Value > 0 then
07            char.Torso.Poison.Enabled = true
08            while char.charactervalues.Venom.Value >= 0 do
09                char.Humanoid.Health -= 3
10                wait(0.8)
11            end
12        else
13            char.Torso.Poison.Enabled = false
14        end
15        debounce = false
View all 28 lines...
Ad

Answer this question