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

Is there any way to play an animation using UserInputService?

I want to play an animation when a player presses W but it doesn't seem to work, there are no errors that show up in the output so I don't know what to do.

Here is the script:

local HumanoidRootPart = script.Parent:WaitForChild("HumanoidRootPart")
local Humanoid = HumanoidRootPart.Cube.Humanoid

local animation = script:WaitForChild("Walk")
local Walk = Humanoid:LoadAnimation(animation)

game:GetService("UserInputService").InputBegan:connect(function(input,gameprocessed)
	if input.KeyCode == Enum.KeyCode.W then
		Walk:Play()
	end
end)

game:GetService("UserInputService").InputEnded:connect(function(input,gameprocessed)
 if input.KeyCode == Enum.KeyCode.W then
 	Walk:Stop()
  end
end)

2 answers

✓ Accepted answer

Hi there, great question! Here's how you would do it.

local UserInputService = game:GetService("UserInputService")  --gets userinputservice, so we can use it
local Animation = script.Walk --reference variable for your walk animation, (make sure your animation object has the animation id in it, and that the anim works.)
 
UserInputService.InputBegan:Connect(function(Input)  --event for when the input begins, and assigns the input to "Input"
    if Input.KeyCode == Enum.KeyCode.W then  --if statement saying if the input is equal to the keycode w, then
        local Player = game.Players.LocalPlayer --reference variable for your localplayer, which is each person's unique player
        local Character = Player.Character --reference variable for your localplayer's character
        local Humanoid = Character:WaitForChild("Humanoid") --gets the humanoid, with WaitForChild, incase the humanoid hasn't loaded yet
       
        local AnimationTrack = Humanoid:LoadAnimation(Animation)  --loads the animation, while passing the animation object through it
        AnimationTrack:Play()  --plays the animation
    end
end)

Make sure to try to understand the code, and this should work. Have a nice day!

5 comments

0

It still doesn't work, I'm using a ServerScript and its parent is StarterCharacterScripts I'm not sure why it won't work but thank you for trying anyway.

0

I'm sure the animation works because when I do AnimationTrack:Play() without the uis it works fine

0

UserInputService only works for LocalScripts, so make sure it's a LocalScript, and put it in StarterPlayerScripts.

0

It works fine now! Thank you so much!

0

No problem. Glad I could help!

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