PcoWSkbVqDnWTu_dm2ix
We use cookies on this site to enhance your user experience

Play AnimationTrack for a Number of Loops

Play AnimationTrack for a Number of Loops

Jun 26 2018, 11:09 AM PST

The function in this code sample will play an AnimationTrack on a loop, for a specific number of loops, before stopping the animation.

In some cases the developer may want to stop a looped animation after a certain number of loops have completed, rather than after a certain amount of time. This is where the DidLoop event can be used.

local function playForNumberLoops(animationTrack, number)
	animationTrack.Looped = true
	animationTrack:Play()
	local numberOfLoops = 0
	local connection = nil
	connection = animationTrack.DidLoop:connect(function()
		numberOfLoops = numberOfLoops + 1
		print("loop: ", numberOfLoops)
		if numberOfLoops >= number then
			animationTrack:Stop()
			connection:Disconnect() -- it's important to disconnect connections when they are no longer needed
		end
	end)
end