Search code examples
luascriptingroblox

"attepted to index nil with Humanoid"


local animationstomp = script.Animation
local user = game:GetService("UserInputService")
local player = game.Players.LocalPlayer
local char = player.Character
local human = char.Humanoid
user.InputBegan:Connect(function(input, proccesedevent)
if input.KeyCode == Enum.KeyCode.F then
    local animationtrack = human:LoadAnimation(animationstomp)
    
animationtrack:play()
    end 
    end
end)

this script keeps returning error "attempted to index nil with huamnoid" i have looked for solutions on dev forum and on stack overflow but i could not find anything so im going to post myself. anyone catch any erros?


Solution

  • "attempted to index nil with huamnoid" What that means is that this script loaded before the player's character loaded in.


    To fix this, you can use

    local char = player.Character or player.CharacterAdded:Wait() 
    -- uses the player if it's already loaded in, or waits for the character to load in
    

    Also make sure to use

    local human = char:WaitForChild("Humanoid") 
    -- to make sure you wait till the humanoid gets added
    

    Final script

    local animationstomp = script.Animation
    local user = game:GetService("UserInputService")
    local player = game.Players.LocalPlayer
    local char = player.Character or player.CharacterAdded:Wait()
    local human = char:WaitForChild("Humanoid")
    user.InputBegan:Connect(function(input, proccesedevent)
       if input.KeyCode == Enum.KeyCode.F then
            local animationtrack = human:LoadAnimation(animationstomp)
            animationtrack:play()
        end
    end)