Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Why am I getting a humanoid nil error?

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

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)

2 comments

0

But sometimes, CharacterAdded will fire even when the character model's parent is nil (or not parented to the workspace yet)

0

Nope, still the same message.

This discussion is preserved as it was. New answers, comments, and votes are closed.