Roblox 尝试用 'WaitForChild' 索引 nil

Roblox Attempt to index nil with 'WaitForChild'

我正在制作一个脚本,该脚本应该找到目标玩家,如果玩家内部的值为真,则 MoveTo()。它输出一个错误说 Attempt to index nil with 'WaitForChild' 这是一个服务器脚本,错误位于 plr:WaitForChild("Crime",1)。 这是:

local crime= false
local plr = nil

function findNearestTorso(pos)
    local list = game.Workspace:children()
    local torso = nil
    local dist = 10000
    local temp = nil
    local human = nil
    local temp2 = nil
    for x = 1, #list do
        temp2 = list[x]
        if (temp2.className == "Model") and (temp2 ~= script.Parent) then
            temp = temp2:findFirstChild("HumanoidRootPart")
            human = temp2:findFirstChild("Humanoid")
            if (temp ~= nil) and (human ~= nil) and (human.Health > 0) then
                if (temp.Position - pos).magnitude < dist then
                    plr = game.Players:WaitForChild(temp2.Name,1)
                    print("plr")
                    torso = temp
                    dist = (temp.Position - pos).magnitude
                end
            end
        end
    end
    return torso
end

while true do
    wait(1)
    local target = findNearestTorso(script.Parent.HumanoidRootPart.Position)
    if target ~= nil and plr:WaitForChild("Crime",1).Value==true then
        script.Parent.Humanoid:MoveTo(target.Position, target)
    end

end

您不能保证 plrfindNearestTorso 运行后设置。

您在 3 个嵌套 if 语句的正文中设置了 plr

if (temp2.className == "Model") and (temp2 ~= script.Parent) then
    --...
    if (temp ~= nil) and (human ~= nil) and (human.Health > 0) then
        if (temp.Position - pos).magnitude < dist then
            plr = game.Players:WaitForChild(temp2.Name,1)
            --...

如果您的任何 if 语句不正确 plr 将是 nil

为了解决这个问题,我们可以简单地更改发生错误的条件,在尝试调用 plr:WaitForChild

之前检查 plr 是否为 nil
if target ~= nil and plr ~= nil and plr:WaitForChild("Crime",1).Value==true then