【问题标题】:Roblox Attempt to index nil with 'WaitForChild'Roblox 尝试使用“WaitForChild”索引 nil
【发布时间】:2021-09-23 19:27:46
【问题描述】:

我正在制作一个脚本,它应该找到目标玩家,如果玩家内部的值为真,那么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

【问题讨论】:

  • 如果 Nifim 回答了您的问题,请将其标记为解决方案。

标签: lua roblox


【解决方案1】:

您不能保证在findNearestTorso 运行之后设置plr

您在 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-16
    • 2022-12-24
    • 2021-03-30
    • 2021-09-30
    • 1970-01-01
    • 2020-11-22
    相关资源
    最近更新 更多