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)
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