Attempt to index nil with 'Stop' (AnimationTrack)

I’m working on a small hangout with some simple emotes/animations that players can do. I have a LocalScript that uses this code:

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

player.CharacterAdded:Connect(function(character)
	char = character
end)    

local currentAnim

local sit = false

uis.InputBegan:Connect(function(input,proc)
	if not proc then
		if input.KeyCode == Enum.KeyCode.B or input.KeyCode == Enum.KeyCode.DPadDown then
			sit = not sit
			if sit == true then
				local humanoid = char:FindFirstChildOfClass("Humanoid")
				local animation = Instance.new("Animation")
				animation.AnimationId = "rbxassetid://6571097367" --My sit animation
				if humanoid then
					local animator = humanoid:FindFirstChildOfClass("Animator")
					if animator then
						local animationTrack = animator:LoadAnimation(animation)
						animationTrack:Play()
						return animationTrack
					else
						animator = Instance.new("Animator", humanoid)
						local animationTrack = animator:LoadAnimation(animation)
						currentAnim = animationTrack
						currentAnim:Play()
					end
				end
			else
				currentAnim:Stop()
			end
		end 
	end
end)

It throws the error: Players.A_thruZ.PlayerScripts.LocalScript:35: attempt to index nil with 'Stop'. I don’t know if I’m just making some silly mistake. Help is appreciated.

it’s probably because currentAnim isn’t fully defined, you only define it in the if statement

when it goes to the else statement, currentAnim hasn’t been defined and you’re using :Stop() on a blank variable

maybe try making the Animation outside of the function? i think it makes a brand new animation every time if sit == true then is true

1 Like

currentAnim is defined outside of the uis.InputBegan event.

Because you’ve said:

local currentAnim

and you have not assigned anything to that variable.

I’m confused. Since the true code within the if statement runs first, shouldn’t currentAnim = animationTrack also be defined already?

yeah but it only says local currentAnim which is just a blank variable, you should define it outside of the function so you only need to define it once

It must be defined before that you use it.

I’ve figured out my silly mistake. There’s an if statement checking if the humanoid has an Animator and currentAnim is only defined within the else.

yeah, you didn’t define currentAnim in the if statement checking if there’s an animator or not lol

1 Like

At the red point you start check if another variable is true and if the rest of the things following are true the script will define the variable at the green point, if sit isn’t true the script cannot assigne a value to the variable and it will result nil at the blue point.