Task.cancel() and tween states

Hey, and thanks for reading in advance.

I’m crafting a little coding-helper project for a friend of mine who’s attempting to make an RPG - I basically just wanted to code an isolated system for changing music / lighting / showing an area title card based on your location within specific regions.

I’m basically done, but one last annoying bug is getting in the way of it being complete:

image

I’m tweening a number value (BGMTransitionMultiplier) to interpolate the audio for the area’s BGM from silent to full volume / vice versa upon entering/exiting an area. It works, but only if you fully allow the tweens to play out before changing areas.

I attempted to code safety measures to handle cancelling the current fade task and the active tweens, but to no avail - if you quickly switch areas, the fading tweens will cancel correctly the first time, but will not manipulate the numbervalue when played again afterwards, and the issue doesn’t correct itself until you allow them to fully play out again.

Stranger still, the tweens are behaving as if they are being played, with print confirmations in the output showing such.

Here’s the code explicitly handling changing the BGM:

function NewSong(Song)
	if Current_MusicSwap_Task then
		task.cancel(Current_MusicSwap_Task)
		BGM_Transition_FadeIn:Cancel()
		BGM_Transition_FadeOut:Cancel()
	end
	
	if Current_Song == Song then
		Current_MusicSwap_Task = task.spawn(function()
			if Music_Audio.IsPlaying then
				if not Song or Music_Audio.SoundId ~= "rbxassetid://"..Song then
					BGM_Transition_FadeOut:Play()
					BGM_Transition_FadeOut.Completed:Wait()
					
					Music_Audio:Stop()
					DistanceScalar.Value = 0
				end
				
				print('FadeOut Complete')
			end
			
			if Song then
				if Music_Audio.SoundId ~= "rbxassetid://"..Song then
					Music_Audio.SoundId = "rbxassetid://"..Song
				end
				
				if not Music_Audio.IsPlaying then
					Music_Audio:Play()
				end

				BGM_Transition_FadeIn:Play()
				BGM_Transition_FadeIn.Completed:Wait()
				
				print('FadeIn Complete')
				
			else
				Music_Audio.SoundId = ""
				DistanceScalar.Value = 0
			end

			Current_MusicSwap_Task = nil
		end)
	end
end

I sadly can’t attach a video, so the repro file will have to do:
LocaleExpo.rbxl (71.2 KB)

Any help or advice is appreciated.

Instead of :Cancel(), try :Destroy(), and then recreate the tweens at the start of the Current_MusicSwap_Task. It might not be an option you’d like but it helps pinpoint the issue, if you still have it.