How to fix this error/bug

I got it to work but a error comes up
“Workspace.Dummy.HealthManager:5: attempt to index nil with ‘HeadUI’”

The script does what I want but I don’t know how to remove this error and why it’s it came up

local Folder = script.Parent

for i, EachNPC in Folder:GetChildren() do
	local Head = EachNPC:FindFirstChild("Head")
	local HeadUI = Head.HeadUI.UI.HealthUI

	local Humanoid = HeadUI.Parent.Parent.Parent.Parent:FindFirstChild("Humanoid")
	HeadUI.HealthNum.Text = math.floor(Humanoid.Health) .. " / " .. math.floor(Humanoid.MaxHealth)
	function updateHealth()

		HeadUI.HealthNum.Text = math.floor(Humanoid.Health) .. " / " .. math.floor(Humanoid.MaxHealth)
		local pie = (Humanoid.Health / Humanoid.MaxHealth)
		HeadUI.Healthbar.Size = UDim2.new(pie, 0, 1, 0)
	end
	Humanoid.HealthChanged:Connect(updateHealth)
end

you could try adding a sanity check to check if there is a head and if there is then it runs, for example

local head = blabla
local HeadUI
if head then
HeadUI = bla bla
else
return
end

if that don’t solve it try changing the FindFirstChild to WaitForChild

You where right about changing the FindFirstChild to WaitForChild I changed this line and now it works

Old

local Humanoid = HeadUI.Parent.Parent.Parent.Parent:FindFirstChild("Humanoid")

New

local Humanoid = HeadUI.Parent.Parent.Parent.Parent:WaitForChild("Humanoid")