Animation script doesnt stop

Why doesnt the animation stop after 9 seconds does anyone know why

-- ServerScript in ServerScriptService

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Players = game:GetService("Players")

-- Replace "YourRemoteEventName" with the name of your RemoteEvent
local remoteEvent = script.Parent.RemoteEvent
-- Replace "YourAnimationId" with your animation ID
local animationId = "139708044238037"

local function onRemoteEventFired(player)
	local character = player.Character
	if not character then return end

	local humanoid = character:FindFirstChildOfClass("Humanoid")
	if not humanoid then return end

	-- Create and configure the Animation
	local animation = Instance.new("Animation")
	animation.AnimationId = "rbxassetid://" .. animationId

	-- Create and configure the AnimationTrack
	local animationTrack = humanoid:LoadAnimation(animation)
	animationTrack.Looped = false -- Ensure the animation does not loop per play
	animationTrack.Priority = Enum.AnimationPriority.Action -- Set priority to ensure it does not blend

	local startTime = tick() -- Record the start time
	local loopDuration = 9 -- Duration to loop in seconds

	-- Play the animation repeatedly for 9 seconds
	while tick() - startTime < loopDuration do
		animationTrack:Play()
		wait(animationTrack.Length) -- Wait for the animation to finish before replaying
	end
end

-- Connect the RemoteEvent's OnServerEvent to the function
remoteEvent.OnServerEvent:Connect(onRemoteEventFired)

Try replacing this

local startTime = tick() -- Record the start time
	local loopDuration = 9 -- Duration to loop in seconds

	-- Play the animation repeatedly for 9 seconds
	while tick() - startTime < loopDuration do
		animationTrack:Play()
		wait(animationTrack.Length) -- Wait for the animation to finish before replaying
	end

with this:

local animate = task.spawn(function()
    while true do
        animationTrack:Play()
        task.wait(animationTrack.Length)
    end
end)
task.wait(loopDuration)
task.cancel(animate)
animationTrack:Stop()

Please let me know if this worked !

PS: you could also set animationTrack.Looped = true and you wouldn’t have to replay the animation every time in the while true do ... end.

1 Like

Thanks so much it did worked!!!

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