While loop tween problem

I’m trying to create an obstacle in my obby that sweeps across the floor and back using tweens. The tween repeats by wrapping the function in a while loop. However, as you can see in the clip, when the reverse tween plays it’s abruptly stopped and the first tween plays, creating a loop where the reverse tween keeps on getting interrupted.

External Media

Here’s my code:


local sweepIntervalAndStyle = TweenInfo.new(5, Enum.EasingStyle.Linear)

local sweepingKillbrickGoal = {
	Position = Vector3.new(9.423, 9.718, -98.921)
}

local reverseSweepingKillbrickGoal = {
	Position = Vector3.new(9.423, 9.718, -162.497)
}

local sweepTween = TweenService:Create(sweepingKillbrick, sweepIntervalAndStyle, sweepingKillbrickGoal)

local reverseSweepTween = TweenService:Create(sweepingKillbrick, sweepIntervalAndStyle, reverseSweepingKillbrickGoal)

function SweepAndReverse()
	sweepTween:Play()
	sweepTween.Completed:Connect(function()
		reverseSweepTween:Play()
	end)
end

while true do
	task.wait(0.5)
	SweepAndReverse()
end

For some reason, the problem fixes itself if I call SweepAndReverse() normally without using a while loop. However, I want the sweeping to repeat. Help would be majorly appreciated.

Try waiting for each tween to prevent them from getting interrupted.

function SweepAndReverse()
	sweepTween:Play()
	sweepTween.Completed:Wait()
	reverseSweepTween:Play()
	reverseSweepTween.Completed:Wait()
end

while true do
	SweepAndReverse()
end

You can condense this further by using the tween itself as a loop by using -1 on repeat count and reverses to true making the while true do and reverse tweens unnecessary

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.