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

How do I identify the Character & Humanoid in ROBLOX?

I have been trying to make it so the GUI shows the Players Max Health which increases every level. However it's as if everything I try doesn't work right, and only works half of the time. Sometimes it will find the Character, sometimes it wont. I've tried everything I could think of but it wont fix. Can someone help me please? The code is inside a Local script in the PlayerGui. This is the Code:

local player = game.Players.LocalPlayer
local Char = player.Character
local Humanoid = Char.Humanoid
local LevelData = player:WaitForChild('LevelData')
local Level = LevelData:WaitForChild('Level')

while true do
	wait(0.2)
	Humanoid.MaxHealth = 100+(3*(player.LevelData.Level.Value*player.PlayerGui.BonusDamage.Value))
	player.PlayerGui.Power.Value = Humanoid.MaxHealth
	script.Parent.Text = Humanoid.MaxHealth
end

The error output in-game on the ROBLOX Developer Console in the Client Log is:

Players.Knucklehead_Ninja.PlayerGui.Stats.Frame.HealthNumber.LocalScript:3: attempt to index local 'Char' (a nil value)
Stack Begin
Script 'Players.Knucklehead_Ninja.PlayerGui.Stats.Frame.HealthNumber.LocalScript', Line 3
Stack End

1 answer

✓ Accepted answer

Keep in mind that this code inside a player's PlayerGui might run before the player's character has a chance to load. In such a case, running

local Char = player.Character

will just set Char to nil, which will create an error when you try to index it. You need to wait for the character to load first before you can use it. You can accomplish this by running something like

local Char
repeat
	Char = player.Character
	wait()
until Char

before running the rest of your code. To be on the safe side, you should also access the humanoid by

local Humanoid = Char:WaitForChild("Humanoid")

just in case the humanoid doesn't load immediately once player.Character is assigned.

3 comments

0

Thanks so much this works perfectly. ^_^

0

Please accept this answer if it answers your question.

1

Just a heads up, but you can simply do local char = player.Character or player.CharacterAdded:wait().

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