Keybind Toggle for Animation

How can I make it so where you can press T again after the animation is activated to turn it off? Sorta like a toggle.

local UIS = game:GetService(‘UserInputService’)
local Player = game.Players.LocalPlayer
local Character = Player.Character or Player.CharacterAdded:Wait()

local Key = ‘T’

local Animation = Instance.new(‘Animation’)
Animation.AnimationId = ‘rbxassetid://4515171742’

local Debounce = true

UIS.InputBegan:Connect(function(Input, IsTyping)
if IsTyping then return end
local KeyPressed = Input.KeyCode
if KeyPressed == Enum.KeyCode[Key] and Debounce then
Debounce = false
local LoadAnimation = Character.Humanoid:LoadAnimation(Animation)
LoadAnimation:Play()
wait(2)
Debounce = true
end
end)

The LoadAnimation needs to be outside of InputBegan so that any future keybind presses will refer to the same animation track rather than a new one. Every time you call LoadAnimation, animation data is loaded from a cache or the Animation object and put into a new AnimationTrack.

As for keybinds, just add an extra variable that holds a boolean value. Flip this each time InputBegan is called. If it’s true, proceed with the animation playing bit of the script. If it’s false, then call stop on the animation track.

5 Likes