Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How do I have an animation start and stop playing under specific circumstances?

Asked by 4 years ago

I'm trying to have a sprinting animation that plays when the walk speed is above 16. I could have it so that it plays when the player presses shift and stops when shift is released, but I have a stamina bar that automatically changes the walkspeed back to normal when it depletes, so having it play with left shit wouldn't work. The code that I have successfully plays the animation, but it has issues stopping it. I get an error saying "attempt to index nil with 'Stop'", which sometimes keeps the animation on loop even after I stop moving and other times works perfectly until somewhere down the line the animation loops again. Here's the script:

01local character = script.Parent
02local Humanoid = character:WaitForChild("Humanoid")
03local moving = false
04local RunService = game:GetService("RunService")
05 
06Humanoid.Running:Connect(function(speed)
07    if (speed > 17) then
08        moving = true
09        Anim = Instance.new('Animation')
10        Anim.AnimationId = 'rbxassetid://5516129289'
11        PlayAnim = character.Humanoid:LoadAnimation(Anim)
12        PlayAnim:Play()
13    else
14        moving = false
15        PlayAnim:Stop()
16    end
17end)

1 answer

Log in to vote
0
Answered by
I_Nev 200 Moderation Voter
4 years ago
Edited 4 years ago

You was only telling it what the animation was on the first line:

01local character = script.Parent
02local Humanoid = character:WaitForChild("Humanoid")
03local moving = false
04local RunService = game:GetService("RunService")
05local Anim = Instance.new('Animation')
06Anim.AnimationId = 'rbxassetid://5516129289'
07local PlayAnim = character.Humanoid:LoadAnimation(Anim)
08 
09Humanoid.Running:Connect(function(speed)
10    if (speed > 17) then
11        moving = true
12        PlayAnim:Play()
13    else
14        moving = false
15        PlayAnim:Stop()
16    end
17end)

Let me know if this fixes your issues ~nevan

0
Oh wow, I had no idea the problem was something so simple like this. Thank you! LeedleLeeRocket 1257 — 4y
0
No problem:) I_Nev 200 — 4y
Ad

Answer this question