Animation or script problem

Hi

I have a tool which is supposed to play and stop an animation when equipped and unequipped.
The problem is that the animation doesn’t stops after unequipped.
The animation is supposed to play for every character.
Code:

wait(0.1)

script.Parent.Kicking.Changed:Connect(function()
	if script.Parent.Kicking.Value == true then
		for _,player in pairs(game.Players:GetPlayers()) do
			local character = player.Character
			anim = character.Humanoid:LoadAnimation(script.Parent.dance):Play()
		end
	elseif script.Parent.Kicking.Value == false then
		anim:Stop()
	end
end)

Error:
Players.octav20071.Backpack.Tool.Anim:10: attempt to index nil with ‘Stop’ - Client - Anim:10
21:31:14.064 Stack Begin - Studio
21:31:14.065 Script ‘Players.octav20071.Backpack.Tool.Anim’, Line 10

Any help?

local _anims = {} -- create a table to hold all the animations

script.Parent.Kicking.Changed:Connect(function()
	if script.Parent.Kicking.Value then
		for _,player in pairs(game.Players:GetPlayers()) do
			local character = player.Character
			local _anim = character.Humanoid:LoadAnimation(script.Parent.dance)
            _anim:Play() -- play it separately, ":Play()" doesn't return anything 
            table.insert(_anims, _anim) -- insert the animationtrack into the table so it can be stopped
		end
	elseif not script.Parent.Kicking.Value then
        for _, track in ipairs(_anims) do -- loop through all the animation tracks and stop them
		    track:Stop()
        end
	end
end)

There were a few issue in your code

2 Likes

Thank you, I did some changes from a local script to server script, to be replicated to all clients. Again, thank you so much!

1 Like

To add onto what @HugeCoolboy2007 did, this is just preference but if you’re checking if a value is true or not, for the 2nd condition (if the value wasn’t true or false), you can just use else instead of an else if. So with his example, it would be

local _anims = {} -- create a table to hold all the animations

script.Parent.Kicking.Changed:Connect(function()
	if script.Parent.Kicking.Value then
		for _,player in pairs(game.Players:GetPlayers()) do
			local character = player.Character
			local _anim = character.Humanoid:LoadAnimation(script.Parent.dance)
            _anim:Play() -- play it separately, ":Play()" doesn't return anything 
            table.insert(_anims, _anim) -- insert the animationtrack into the table so it can be stopped
		end
	else
        for _, track in ipairs(_anims) do -- loop through all the animation tracks and stop them
		    track:Stop()
        end
	end
end)

This basically means that if Kicking’s value wasn’t true, then do what’s after the else, keep in mind this will only work if you’re only checking one value and that value is a BoolValue

1 Like