Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

How do I make an animation play when a tool is clicked?

Here is the local script I attempted to make:

local Player = game.Players.LocalPlayer
local Character = Player.Character or Player.CharacterAdded:wait()
local humanoid = Character:WaitForChild("Humanoid")
local anim = script.Parent.shoot
 
script.Parent.MouseButton1Click:Connect(function(key)
	local animTrack = humanoid:LoadAnimation(anim)
	animTrack:Play()
end)

2 answers

It is best that you load the animation first as your script is making the animation load everytime the parent is clicked on.

Also, I'm assuming you want it based on a tool as MouseButton1Click is meant for GUI buttons. An alternative is the Activated event if your script's parent is a Tool instance.

If you experience an error called Humanoid is not a descendant of DataModel then replace this with your variable humanoid:

local humanoid = player.Character:WaitForChild("Humanoid") -- yes, use exactly player.Character, I find that using the character variable doesn't work for me sometimes.

while humanoid and not humanoid:IsDescendantOf(workspace) do
    humanoid.AncestryChanged:Wait()
end

And another minor tip, your :wait() should be :Wait(). :wait() is deprecated.

You could use this script, and your flaw is you have to make sure that you set your character variable to the tool's parent. The major flaw is that you used a mousebutton1click event to try to detect when the tool is clicked. The way to do this, is to use a Activated event.

local Tool = script.Parent --reference variable for the tool
local Anim = Tool.Shoot --reference variable for the animation object
local Character = Tool.Parent --defining the character variable, you have to set it to your tool's parent, as I said before.
local Humanoid = Character:WaitForChild("Humanoid") --variable for the humanoid, and waiting for it incase it hasn't loaded yet.

Tool.Activated:Connect(function() --event for when the tool is activated, aka clicked when the tool is equipped.
    local AnimationTrack = Humanoid:LoadAnimation(Anim) --loads the animation through the humanoid, and passes your anim variable which is equal to your anim object.
    AnimationTrack:Play() --plays the animation
end) --end

Hopefully this helps, this script should work! Make sure to try to understand it first, for your benefit. Have a great day!

This discussion is preserved as it was. New answers, comments, and votes are closed.