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

Players.n1ksutin123.Backpack.LocalScript:6: attempt to index local 'char' (a nil value)?

I'm having a weird problem with my health number thingy.

local plr = game.Players.LocalPlayer
local char = plr.Character
local hp = game.StarterGui.Bar.Frame.HP

while true do
	wait(0.001)
	local Health = char.Humanoid.Health
	hp.Text = "%".. Health
end

2 comments

0

put the script in starter character scripts

0

that isn't needed, local scripts can work anywhere on the client

1 answer

✓ Accepted answer

You're doing several things wrong.

First: you want to make sure the Character has loaded in before you assign it to a variable, Second: You're indexing "StarterGui" instead of the player's PlayerGui.

Also, just as a tip, the minimum wait time for Lua is 1/60. There is no reason for you to try to update it faster or every 1/60th of a second. Please just use the HealthChanged event of the humanoid.

Here's an improved script:

local Players = game:GetService("Players") -- The Players service
local LocalPlayer = Players.LocalPlayer; -- The local player
local HealthBar = LocalPlayer.PlayerGui:WaitForChild("Bar"):WaitForChild("Frame"):WaitForChild("HP");
local Connection;


function newCharacter (character)
	local Humanoid = character:FindFirstChildOfClass("Humanoid");
	if Humanoid then
		if Connection then Connection:disconnect() end
		Connection = Humanoid.HealthChanged:Connect(function()
			HealthBar = Humanoid.Health .. "%"
		end)
	else
		warn("No humanoid found!");
	end 
end

local Character = LocalPlayer.Character or LocalPlayer.CharacterAdded:Wait()
newCharacter(Character);

LocalPlayer.CharacterAdded:Connect(newCharacter);

2 comments

0

thanks but when I played the game in studio it sayd : Attempt to connect failed: Passed value is not a function

0

Sorry about that, I fixed it just now.

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