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

How can I prevent this code from being ran before this for loop finishes?

Asked by 4 years ago
Edited 4 years ago
while true do
    game:GetService("RunService").Heartbeat:Wait()
    if(sound.TimePosition >= 73.8) and (not fade) then
        fade = true
        for i = 0, 1, -0.1 do
            sound.Volume = i
            wait(0.5)
        end
        sound.TimePosition = 0
        for i = 0, 1, 0.1 do
            sound.Volume = i
            wait(0.5)
        end
        fade = false
    end
end

sound.TimePosition = 0 is being ran before the for loop finishes, causing the audio to abruptly jump back to the beginning instead of slowly fading out, then going back to the beginning after the fade finishes. I can confirm that this is the issue as I have another script printing the audio's TimePosition every heartbeat. No other scripts are affecting the audio.

1 answer

Log in to vote
0
Answered by
Psudar 882 Moderation Voter
4 years ago

It's probably because you're stepping with -0.1 even though your goal is 1 in the first loop. As well as this, checking the time can be pretty hacky. I'd recommend using the Sound.Ended event.

In addition to using an infinite loop, i think it might be better if you just set the Loop property of the sound object to true, then use the Ended and Played event instead.

Sound.Looped = true

Sound.Played:Connect(function()
    --fade in
    for i = 0, 1, 0.1 do
        Sound.Volume = i
        wait(0.5)
    end
end)

Sound.Ended:Connect(function()
    --fade out
    for i = 1, 0, -0.1 do
        Sound.Volume = i 
        wait(0.5)
    end
end)

Hopefully this helps.

0
I'm using a loop because I want the song to fade out before the song actually ends. Also, this solution would cause the fade out to begin *after* the audio has already ended. I don't need the song to fade out precisely at 73.8 seconds, and I understand that my solution is hacky. hpenney2 53 — 4y
0
Also, my goal *is* to get to 0 in the first loop. hpenney2 53 — 4y
0
good point, my bad. i wasnt thinking about the ended event. surely you can use it for .Played tho. as for .ended, just replace it with waiting for the time and such. Psudar 882 — 4y
Ad

Answer this question