Attempt to index nil with Humanoid error

I am trying to make a health bar for a game, but when I try to detect when the health changes it just gives me the error, “Attempt to index nil with Humanoid”, and it only happens when I put the function outside of any other function.

Local Script

local hum = player.character.Humanoid

hum.HealthChanged:Connect(function(health)
	local healthGui = player.PlayerGui.HealthGui

	healthGui.Frame.HealthBar.Size = UDim2.new(health/100, -5, 0.8, 0)
end)
5 Likes

Are you defining player? , If this is a local script define player by:

local player = game:GetService("Players").LocalPlayer
2 Likes

I defined the player like

local player = game.Players.LocalPlayer
2 Likes

try this:

local player = game:GetService("Players").LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()
local humanoid = character.Humanoid

humanoid.HealthChanged:Connect(function(health)
	local healthGui = player.PlayerGui.HealthGui
	healthGui.Frame.HealthBar.Size = UDim2.new(health/100, -5, 0.8, 0)
end)

im not sure how fast you’re defining the humanoid, but if you are defining it as soon as the script runs it will error

12 Likes

this gives me an error: ServerScriptService.BendingEvent:5: attempt to index nil with ‘Wait’
in the line containing local character = player.Character or player.CharacterAdded:Wait()