Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Why am I getting a humanoid nil error?

Asked by 1 year 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 1 year ago
Edited 1 year 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 2189 — 1y
0
Nope, still the same message. kickoff127 103 — 1y
Ad

Answer this question