Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

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

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:

local character = script.Parent 
local Humanoid = character:WaitForChild("Humanoid")
local moving = false
local RunService = game:GetService("RunService")

Humanoid.Running:Connect(function(speed)
    if (speed > 17) then
		moving = true
		Anim = Instance.new('Animation')
		Anim.AnimationId = 'rbxassetid://5516129289'
		PlayAnim = character.Humanoid:LoadAnimation(Anim)
		PlayAnim:Play()
    else
		moving = false
		PlayAnim:Stop()
    end
end)

1 answer

✓ Accepted answer

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

local character = script.Parent 
local Humanoid = character:WaitForChild("Humanoid")
local moving = false
local RunService = game:GetService("RunService")
local Anim = Instance.new('Animation')
Anim.AnimationId = 'rbxassetid://5516129289'
local PlayAnim = character.Humanoid:LoadAnimation(Anim)

Humanoid.Running:Connect(function(speed)
    if (speed > 17) then
        moving = true
        PlayAnim:Play()
    else
        moving = false
        PlayAnim:Stop()
    end
end)

Let me know if this fixes your issues ~nevan

2 comments

0

Oh wow, I had no idea the problem was something so simple like this. Thank you!

0

No problem:)

This discussion is preserved as it was. New answers, comments, and votes are closed.