Help with UserInputService

Hello, fellow devs! I am having trouble with UIS (UserInputService). I want an animation to play when a key is pressed on the player’s keyboard. However, it does not work. This script is inside StarterPlayerScripts. Here is the script.

local player = game.Players.LocalPlayer

player.CharacterAdded:Wait()
player:WaitForChild("Humanoid")

local humanoid = player.Character.Humanoid

local punchAnim = humanoid:LoadAnimation(script.Punch)

UIS.InputBegan:Connect(function(input)
	if UIS.KeyboardEnabled then
		print("Keyboard enabled!")
		if input.UserInputType == Enum.UserInputType.Keyboard then
			print("Keyboard found!")
			if input.KeyCode == Enum.KeyCode.P then
				punchAnim:Play()
				print("Punch anim played!")
			end
		end
	end
end)

Hello TheDevBoi!
First of all, why do you want to check if the user has a keyboard? Just remove all that conditions and make it simple, also, you can use GameProccessed to check if the player is typing inside a textbox:

local player = game.Players.LocalPlayer

player.CharacterAdded:Wait()
player:WaitForChild("Humanoid")

local humanoid = player.Character.Humanoid

local punchAnim = humanoid:LoadAnimation(script.Punch)

UIS.InputBegan:Connect(function(input, gameProccessed)
   if input.KeyCode == Enum.KeyCode.P and gameProccessed == false then
      punchAnim:Play()
      print("Punch anim played!")
   end
end)

Hope that helps!

Your issue could be lying in line 4; you’re yielding your script to wait for a humanoid to be added to the player - consider changing it to player.Character:WaitForChild(“Humanoid”) rather than player:WaitForChild(“Humanoid”).

Thanks to both of your replies! My script is functioning now. Thank you!