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

How do I stop an animation from playing? (UserInputSettings)

Asked by 8 years ago

**Greetings,

I have been trying to make an animation load when a certain key is pressed. Succeeded, however, my problem is how do I make the same animation stop if the same key is pressed? It is a meditating animation.

I put the script down below. I would really appreciate some help.

Best wishes, Amydamaru**

local player = game:GetService("Players").LocalPlayer

local character = player.Character or player.Character:Added()

local humanoid = character:WaitForChild("Humanoid")

local anim = Instance.new("Animation")
anim.AnimationId = "rbxassetid://375479668"

function playAnimation(Anim)
    local track = humanoid:LoadAnimation(Anim)
    track:Play()
end

game:GetService("UserInputService").InputBegan:connect(function(input ,proc)
    if not proc then
        if input.KeyCode == Enum.KeyCode.F then
            playAnimation(anim)
        end
    end
end)

1 answer

Log in to vote
0
Answered by 8 years ago

You'll need to call the Stop() method on the currently playing AnimationTrack.

local player = game:GetService("Players").LocalPlayer

local character = player.Character or player.Character:Added()

local humanoid = character:WaitForChild("Humanoid")

local anim = Instance.new("Animation")
anim.AnimationId = "rbxassetid://375479668"

local track
function playAnimation(Anim)
    track = humanoid:LoadAnimation(Anim)
    track:Play()
end

game:GetService("UserInputService").InputBegan:connect(function(input ,proc)
    if not proc then
        if input.KeyCode == Enum.KeyCode.F then
            if track then -- track already exists
                if track.IsPlaying then -- track is playing, stop and destroy
                    track:Stop()
                    track:Destroy()
                    track = nil
                else -- track already ended, destroy, create, and play again
                    track:Destroy()
                    playAnimation(anim)
                end
            else -- track doesn't exist, create and play
                playAnimation(anim)
            end
        end
    end
end)
0
Thank you very much for your help. Amydamaru 20 — 8y
Ad

Answer this question