Issue with animation (doesnt wanna stop playing)

Hello. I’m having an issue with an animation.

So in a menu when the button is clicked the animation plays, this works fine. But then I wanna stop playing the animation if the animation is playing and the button is clicked again.

local animations = game.ReplicatedStorage.Animations.Anims
local events = game.ReplicatedStorage.Animations.Events

local animPlaying = false

events.Salute.OnServerEvent:Connect(function(plr)
	local Anim = Instance.new("Animation")
	Anim.AnimationId = animations.Salute.AnimationId
	local track
	
	print(animPlaying)
	
	
	if animPlaying == false then
		track = plr.Character.Humanoid:LoadAnimation(Anim)
		track.Priority = Enum.AnimationPriority.Action
		track.Looped = false
		track:Play()
		animPlaying = true
		
	elseif animPlaying == true then
		if track then
			track:Stop()
		end
	end
end)

Thank you.

3 Likes

You’re creating a new Animation every single time? If you’re not destroying it you should probably create it outside of the event scope.

This will never run because when it’s not activated it’ll create that variable (that’s locked to the scope of the event) and so when they click it again (and fire the event) the variable will not be saved.

Sorry for the potential confusion but here’s what I mean:

local animations = game.ReplicatedStorage.Animations.Anims
local events = game.ReplicatedStorage.Animations.Events

local animPlaying = false
local track
-- move the track variable here

events.Salute.OnServerEvent:Connect(function(plr)
	local Anim = Instance.new("Animation")
	Anim.AnimationId = animations.Salute.AnimationId
	
	print(animPlaying)
	
	
	if animPlaying == false then
		track = plr.Character.Humanoid:LoadAnimation(Anim)
		track.Priority = Enum.AnimationPriority.Action
		track.Looped = false
		track:Play()
		animPlaying = true
		
	elseif animPlaying == true then
		if track then
			track:Stop()
		end
	end
end)

By moving the track variable, you can still access the same Animation track even after the event finishes running and it runs again

2 Likes

I tried that. Didn’t work.

asijdashuidsa

1 Like

Before the if statement can you print out the track variable to see if it is an instance or not? And then try printing the Id of it if it does

1 Like

Hello. Sorry for the delayed response.

I added the print(track) to before the if statement, and this is the result

I clicked the salute button twice, and it printed this:
image

Dont know if this is what you’re looking for.