Help with animation script

Hello, could someone help me with this script please? :frowning:

I need to play an animation when press the G key, how do I do that?

animation id: 6519828327

my script:

local UserInputService = game:GetService("UserInputService")

local function onInputBegan(input, gameProcessed)
	if input.KeyCode == Enum.KeyCode.G then
		-- code to play animation here:
		
	end
end

UserInputService.InputBegan:Connect(onInputBegan)

I recommend using ContextActionService for this, because when you type something with the letter “G” in chat, the “animation” will play. And contextactionservice will create a button for mobile users.

Hi, @PipeSader! Here is a fix of your script, currently!

local UserInputService = game:GetService("UserInputService")

local function onInputBegan(input, gameProcessed)
if input.KeyCode == Enum.KeyCode.G then
local animationId = 6519828327
local player = game.Players

player.Character:Play(animationId, player.Character)
 end
end)

If it’s do not work please reply to me, I’ll answer in a high time since I need to go to sleep soon.

I just tried it and it doesn’t work, I’m not sure what’s wrong :frowning:

local UserInputService = game:GetService("UserInputService")

local function GetAnimator() : Animator -- function to get the animator
   local player = game.Players.LocalPlayer
   local char = player.Character or player.CharacterAdded:Wait()
   local hum = char:WaitForChild("Humanoid")

   return hum:FindFirstChildOfClass("Animator") -- returns the animator
end

local function onInputBegan(input, gameProcessed)
	if input.KeyCode == Enum.KeyCode.G then
		-- code to play animation here:
		local obj = Instance.new("Animation")
        obj.AnimationId = "rbxassetid://6519828327"

        local animation = GetAnimator():LoadAnimation(obj) -- load the animation
        animation:Play() -- plays the animation
	end
end

UserInputService.InputBegan:Connect(onInputBegan)

Can I get the output or console for possible errrors? NOTE: @HugeCoolboy2007 is probably your solution.

I just tried and it does not work, this should be server script in Workspace or where I put it?

No, this should be a local script in starter character scripts

I know

1 Like

It doesn’t need to be in the Starter Character scripts.

 local player = game.Players.LocalPlayer

local anim = Instance.new("Animation") -- creating a new animation
anim.AnimationId = script.Parent.anim -- setting the animationID
 

  game:GetService("UserInputService").InputBegan:Connect(function(input, event) -- calling the roblox service
    if input.KeyCode == Enum.KeyCode.G and not event then -- if the key pressed is G
	        local playAnim = player.Character:WaitForChild("Humanoid"):LoadAnimation(anim) -- load the animation into the humanoid
	        playAnim:Play() -- play the animation
		    end
	end)

Try this, but make sure to make a local script in Starter Character Script.

1 Like

Thanks a lot! it has helped me!! :smiley: :smiley:

1 Like