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

Why can’t I get a player’s humanoid? [Answered]

I need to access a player’s health value so I can change it, and i have this localscript in starterplayerscripts:

wait(0.1)

local player = game.Players.LocalPlayer

local playername = game.Players.LocalPlayer.Name

local playerchar = player.Character

local humanoid = playerchar.Humanoid

local hunger = player.Hunger

while true do
	wait(3)
	hunger.Value = hunger.Value - 1
end

When I run the game, it gives this error message:

Players.Quantapie.PlayerScripts.Hunger:9: attempt to index nil with 'Humanoid'

Also, I have another localscript in screengui,

wait(0.1)
local health = script.Parent

local player = game.Players.LocalPlayer

local playername = game.Players.LocalPlayer.Name

local playerchar = player.Character

playerchar.Humanoid.Changed:Connect(function()
	health.Value = playerchar.Humanoid.Health
end)

and for some reason that has no problems. Anyone know why? Any help would be appreciated. Thanks!

2 comments

0

I need to see your explorer

1

Do: "local playerchar = player.Character or player.CharacterAdded:Wait()"

2 answers

✓ Accepted answer

The player's character may not have been loaded yet, so you can use CharacterAdded:Wait() to fix this.

local playerchar = player.Character or player.CharacterAdded:Wait() -- coding logic, if player.Character is not true (aka. if it doesnt exist) it'll wait for the player's character to be added

local humanoid = playerchar:WaitForChild("Humanoid") -- Wait for the humanoid too

Hope this helps!

2 comments

0

I'l try it, thanks!

1

I think it works! I thought the wait(0.1) would be enough, but I guess my computers too slow. Thanks alot!

Alright, I'll test your code. And I'll see if I can fix it!

2 comments

0

May I see your explorer? So It will be easier to de-code? Thanks.

0

This should be a comment lol

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