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

Music fading script does not want to work?

Hi, i am making a game wich has different sounds. I want the music to fade whenever it starts or ends, i tried putting a localscript inside the sounds with a played and ended function, however when the song ends it does not work. Could anyone show me a good way to script this?

Old script that did not work (Only works when it starts the sound):

script.Parent.Played:Connect(function()
	local targetvolume = 0.5
	script.Parent.Volume = 0
	while wait() do
		if script.Parent.Volume <= targetvolume - 0.01 then
			script.Parent.Volume = script.Parent.Volume + 0.01
		else
			if script.Parent.Volume == targetvolume then
				break
			end
		end
	end
end)

script.Parent.Ended:Connect(function()
	local targetvolume = 0
	if script.Parent.Playing == true then
		while wait() do
			if script.Parent.Volume >= targetvolume + 0.01 then
				script.Parent.Volume = script.Parent.Volume - 0.01
			else
				if script.Parent.Volume == targetvolume then
					break
				end
			end
		end
	end
end)

1 answer

✓ Accepted answer

The problem here is that you're waiting for the song to end, not waiting for it to come very close to ending. Because the song has already ended, volume will not work.

So, here is some insight:

wait() will yield for approximately 0.03 seconds by default. This means you can do 0.03 * 50 (because you're supposedly decreasing volume 50 times) to get the amount of time needed before the song ends. (You can also do wait() * 50, since wait() returns the amount of time it yields for, in seconds.) This can also be presumed as Sound.TimeLength - timeToFade, which gives you the position to start fading the volume at.

That is all.

1 comment

0

Thanks!

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