Roblox Forum banner

Error: Attempt to index nil with Humanoid.

4.7K views 3 replies 3 participants last post by  Dimentio  
#1 ·
When I try to get a player's Humanoid, I get the following error: "Attempt to index nil with Humanoid".
I tried multiple solutions, like for example adding WaitForChild() or FindFirstChild() functions, but I still get the folowing errors:
"Attempt to index nil with WaitForChild"
"Attempt to index nil with FindFirstChild"

Everything works well if I place my script under StarterCharacterScripts, but in my case I absolutely need to place my script under StarterPack. Please help, I don't understand why I get this error!

In other words:
The following line of the script breaks if the script is placed under StarterPlayerScripts, StarterGui or StarterPack:
local Humanoid = game.Players.LocalPlayer.Character:WaitForChild("Humanoid")
But it works perfectly if under StarterCharacterScripts.
 
#2 ·
StarterCharacterScripts do not run directly. They are templates which get cloned into each player character and only then they run. So for them script.Parent really means a player's character. StarterPack is a bit outdated place for initial items granted to player on each respawn. They end up in the player's backpack. So for them script.Parent means player's backpack. The backpack is really outdated place to keep player's scripts. Now they belong to StarterPlayerScripts and they end up in Player.PlayerScripts. In any case to get to player's character you need to use script.Parent.Parent.Character.
 
#3 ·
To understand this you need to understand how Lua works, if there is a value like a character then great! here is your character but if there is no value the value will be set to nil. It basically takes a bit of time before the character is assinged and in that time the script tries to access the character property and it is nil. In a split second after that the character value is your character but it's too late. You just need to let your script wait until the character value is not nil.