Attempt to index nil with 'Stopped' on AnimationTrack

I want to achieve a script that plays a random animaton on a character model, the issue is that it keeps throwing this error: image

This is the script:

-- / [ Services ] \ --
local ServerStorage = game:GetService("ServerStorage")
local Workspace = game:GetService("Workspace")

-- / [ Animations ] \ --
local AnimationFolder = ServerStorage:WaitForChild("Animations")

-- / [ Character ] \ --
local SomeDudesCharacter = Workspace:WaitForChild("SomeDude")
local SomeDudesHumanoid = SomeDudesCharacter:WaitForChild("Humanoid")

-- / [ Script ] \ --

local CurrentAnimation

while wait() do
	local RandomMath = math.random(10000,50000)
	if RandomMath > 10000 then
		CurrentAnimation = AnimationFolder:WaitForChild("Sit")
	elseif RandomMath > 20000 then
		CurrentAnimation = AnimationFolder:WaitForChild("TurnHeadLeft")
	elseif RandomMath > 30000 then
		CurrentAnimation = AnimationFolder:WaitForChild("TurnHeadRight")
	elseif RandomMath > 40000 then
		CurrentAnimation = AnimationFolder:WaitForChild("ArmsStreching")
	elseif RandomMath > 45000 then
		CurrentAnimation = AnimationFolder:WaitForChild("LegsPlaceSwitching")
	end
	print(CurrentAnimation.Name)
	print(RandomMath)
	local AnimationPlayingRightNow = SomeDudesHumanoid:LoadAnimation(CurrentAnimation):Play()
	AnimationPlayingRightNow.Stopped:Wait()
end

The value AnimationPlayingRightNow is actually nil as you’re defining it as something that ends with :Play(). This might be fine in some other cases, however in this case :Play() returns nothing and therefore indexing .Stopped on it will throw an error.

You can resolve this issue by simply removing :Play() from the defining line and then adding it on a new line below.

1 Like

AnimationPlayingRightNow is nil

It happens because you indexed the variable with :Play() and :Play() returns nil

Here is a possible fix:

local AnimationPlayingRightNow = SomeDudesHumanoid:LoadAnimation(CurrentAnimation)
AnimationPlayingRightNow:Play()
AnimationPlayingRightNow.Stopped:Wait()
1 Like