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

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

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

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.

3 comments

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.

0

Also, my goal is to get to 0 in the first loop.

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.

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