Ad
Log in to vote
0

Why am I getting a humanoid nil error?

Asked by 22 days ago
local player = game.Players.LocalPlayer
local mouse = player:GetMouse()
local hand = player.Character.Humanoid:GetAccessories()[1]

mouse.Button1Down:Connect(function()
    hand.CFrame = CFrame.new(hand.Position, mouse.Hit.p)
end)

That is my script to make my arm follow my mouse. I am getting this error though: 21:28:52.305 Players.name.PlayerScripts.LocalScript:3: attempt to index nil with 'Humanoid' - Client - LocalScript:3 21:28:52.305 Stack Begin - Studio 21:28:52.305 Script 'Players.name.PlayerScripts.LocalScript', Line 3 - Studio - LocalScript:3 21:28:52.305 Stack End - Studio

Can you please help me? Thanks!

1 answer

Log in to vote
1
Answered by 22 days ago
Edited 22 days ago

Error - > attempt to index nil with 'Humanoid'.

This error means that the Character is nil; therefore, you are trying to index 'Humanoid' on nil.

This is due to the character not being loaded at the time the script loads. This is generally resolved by using the CharacterAdded event and using the Wait function, so it will yield until the character gets added. However, since your script is inside player scripts, if the character dies, it will not get the character again.

To fix this, you can put the character inside of the Button1Down event so it will get the character whenever the event fires.

local player = game.Players.LocalPlayer

local mouse = player:GetMouse()

mouse.Button1Down:Connect(function()
    if not player.Character then return end
    local humanoid = player.Character:FindFirstChild("Humanoid")
    if humanoid then
        local hand = humanoid:GetAccessories()[1]
        hand.CFrame = CFrame.new(hand.Position, mouse.Hit.p)
    end 
end)
0
But sometimes, CharacterAdded will fire even when the character model's parent is nil (or not parented to the workspace yet) T3_MasterGamer 1701 — 22d
0
Nope, still the same message. kickoff127 101 — 21d
Ad

Answer this question