Roblox尝试使用'WaitForChild'索引nil

我正在编写一个脚本,它应该可以找到目标玩家,如果玩家内的一个值为true,则进行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
点赞
用户7396148
用户7396148

你不能保证findNearestTorso运行后plr会被设置。你在三个嵌套的if语句中设置了plr。如果你任何一个if语句不成立,plr将是nil。为了解决这个问题,我们可以简单地修改你的条件,检查在尝试调用plr:WaitForChild之前plr是否为nil

如果目标~=nil 并且 plr~=nil 并且 plr:WaitForChild("Crime",1).Value==true,那么处理它
2021-07-14 20:21:05