I have made a module for my project which should easily handle player animations; however no matter what I try I cannot get any looped animations to stop.
Here is the full script:
local moduleAnimator = {}
function moduleAnimator:retrieveAnimator(player)
local animator
if player:IsA("Player") then
animator = player.Character.Humanoid.Animator
else
animator = player.Humanoid.Animator
end
return animator
end
function moduleAnimator:playAnimation(player,animationTrack)
local animator = moduleAnimator:retrieveAnimator(player)
local animTrack = animator:LoadAnimation(animationTrack)
animTrack:Play()
animTrack:AdjustSpeed(1)
end
function moduleAnimator:stopAnimation(player,animationTrack)
local animator = moduleAnimator:retrieveAnimator(player)
local anim = animator:LoadAnimation(animationTrack)
anim:Destroy()
end
return moduleAnimator
I’ve tried a multitude of things however I cannot reach a conclusion, all of the other posts experiencing the same problem never seem to solve the issue either (even ones marked as solved).
Edit:
For further details the way I would do this is store all the data in a table like
local PlayersAnimations = {
["McGamerNick"] = {
walk = animTrackVariable,
dance1 = animTrackVariableFromplayAnimation
}
}
then you can just index it
if PlayersAnimation[player.Name] then
moduleAnimator:playAnimation(player, PlayersAnimation[player.Name].dance1)
end
It’s how I do it in my games, since it’s easier to reference everything, then just set the entry to nil when you are done with it and destroy it from the character’s animator.
First off, Animator:LoadAnimation creates a new track, it does not get a track.
You can use Animator:GetPlayingAnimationTracks which returns an array of AnimationTracks currently playing. Loop through them and check the name against a name you pass.
i.e moduleAnimator:stopAnimation(player, "Idle") to stop the idle animation.
EDIT #2
You need to update your code to actually work with this.
function moduleAnimator:stopAnimation(player, trackName: string)
-- get your animator here
for _, v in Animator:GetPlayingAnimationTracks() do
if v.Name == trackName then
v:Stop()
return
end
end
end
EDIT #3
You should also look into some OOP programming.
Creating an object to handle animations is better than a general purpose module.
(I actually did this before, using this code) function moduleAnimator:stopAnimation(player,animationTrack)
local animator = moduleAnimator:retrieveAnimator(player)
local anim = animationTrack.Name
for _,v in pairs(animator:GetPlayingAnimationTracks()) do
if v.Name == anim then
v:Stop()
return
end
end