'attempt to index nil with "WaitForChild"
i am making a game right now and i want enemies that spawn to have a health bar + player base. All i have been giving this function to has a humanoid. but it will not stop saying attempt to index nil with wait for child at line 16. (This is a module script located in replicated)
local Players = game:GetService("Players")
local health = {}
function health.Setup(model)
local newHealthBar = script.HealthGui:Clone()
newHealthBar.Adornee = model:WaitForChild("Head")
newHealthBar.Parent = Players.LocalPlayer.PlayerGui
health.UpdateHealth()
model.Humanoid.HealthChanged:Connect(function()
health:UpdateHealth(newHealthBar, model)
end)
end
function health.UpdateHealth(gui, model)
local humanoid = model:WaitForChild("Humanoid")
if humanoid and gui then
local percent = humanoid.Health / humanoid.MaxHealth
gui.CurrentHealth.Size = UDim2.new(percent, 0, 0.5, 0)
if humanoid.Health <= 0 then
gui.Title.Text = model.Name .. "Has died"
else
gui.Title.Text = "Health:" .. humanoid.Health .. "/" .. humanoid.MaxHealth
end
end
end
return health
Solution 1:[1]
In health.Setup you call health.UpdateHealth() so in health.UpdateHealth gui and model are nil values.
That's why local humanoid = model:WaitForChild("Humanoid") is causing the observed error.
If you don't provide any arguments to a function all its parameters are nil. nil values may not be indexed as in model:WaitForChild("Humanoid") which is syntactic sugar for model["WaitForChild"](model, "Humanoid") where model["WaitForChild"] is the indexing operation.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Piglet |
