My animation script doesn't work

I have a LocalScript inside a knife tool that I made. The script is supposed to play an equip animation when the knife is equipped, but it isn’t working…

This is the code:

local knife = script.Parent --here we got the knife tool
local pla = game.Players.LocalPlayer --here we got the player
local cha = pla.Character or pla.CharacterAdded:Wait() --here we got the character from the player
local hum = cha:WaitForChild("Humanoid")--here we got the humanoid from the character
if hum then
	local animation = Instance.new("Animation") --here we create a new animation
	animation.Parent = script.Parent --here we put the new animation inside the knife tool
	animation.AnimationId = "rbxassetid://6892348505" --put your animation id here
	local animator = Instance.new("Animator")
	if animator then
		local animTrack = animator:LoadAnimation(animation) --here we load the animation
	end
end

knife.Equipped:Connect(function() --here we make the animation play when we equip the knife
	animTrack:Play() --here the animation plays
end)

knife.Unequipped:Connect(function() --here we make the animation stop when unequipped
	animTrack:Stop() --here the animation stops
end)

Ok the script seems fine, i have to questions:

  1. Does the character play the default walking animation after equipping the tool?
  2. If yes is the animation priority set ot Action?

Shouldn’t you be doing:
local animator = hum:FindFirstChildOfClass("Animator”)
?

I did that before, and It still didn’t work.

Also, I forgot to share the error. The error is:

attempt to index nil with “Play()”

and the “Stop()” as well.

I am not sure, but could it be that the variable is in the if statement and the functions can not get it.

Try defining the Animation outside the if statement.

True, I might need to do that…

Those errors are gone, but now I am getting the Humanoid:LoadAnimation deprecated error. This error states:

LoadAnimation requires the Animator or object to be a descendant of the game object.

Where exactly is animator parented to? That could be the issue. (I noticed you don’t have it parented at all, you simply instanced it but you never set it to anything.)

Oh, you’re right. I forgot about that…

Replace your animator line with this.

What do I need to parent it to?

Whatever model is being animated. Try either a humanoid, the knife object, etc.

Replacing the animator line with @1000knives 's fix, and parenting it, it works now! thanks for the help!

1 Like