Help with toggle animation script

humanoid:LoadAnimation is deprecated , so you should load the animation on the animator instead. You can create an animator using Instance.new() or reference it via the humanoid. Anyways, you don’t need to declare your variables and load the animation within the UserInput function. Just state your variables at the top and when you need to reference it, simply use :Play() and :Stop(). It’s much easier to read, and is consistent.

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

local sitting = false

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

local Humanoid = Character:WaitForChild("Humanoid")
if Humanoid then -- Probably don't need to check the humanoid existence, but it doesn't hurt
	local Animator = Humanoid:FindFirstChildOfClass("Animator")  -- Get the Animator
	if Animator then
		Track = Animator:LoadAnimation(Animation) -- Load the animation
	end
end

UserInputService.InputBegan:Connect(function(input, gameProcessedEvent)

	if input.UserInputType == Enum.UserInputType.Keyboard then
		if input.KeyCode == Enum.KeyCode.Z then	
			if sitting == false then
				Track:Play()
				sitting = true -- Set it to true
			else
				Track:Stop()
				sitting = false -- Set it to false so the bool can run again!
			end
		end
	end
end)
1 Like