尝试使用 "WaitForChild" 索引 nil



我现在正在制作一款游戏,我希望生成的敌人拥有生命条+玩家基础。 我一直在给这个功能一个类人生物。但它不会停止在第 16 行用等待孩子来索引 nil 的尝试。(这是位于复制中的模块脚本)

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

health.Setup中,您称health.UpdateHealth(),因此在health.UpdateHealthguimodel中是零值。

这就是local humanoid = model:WaitForChild("Humanoid")导致观察到的错误的原因。

如果您没有为函数提供任何参数,则其所有参数均为 nil。 nil 值可能不会像model:WaitForChild("Humanoid")中那样被索引,这是model["WaitForChild"](model, "Humanoid")的语法糖,其中model["WaitForChild"]是索引操作。

最新更新