使用“FindFirstChild”和“WaitForChild”获取 NIL

我正在尝试一个名为 Roblox Lua: Scripting For Beginners Leaderboard Script-Through 的书籍中的实例。 我遇到了错误。错误消息是“Workspace.Part.Script:4: attempt to index nil with 'WaitForChild'”。我还遇到了相同的错误信息,用于 FindFirstChild。

这是排行榜脚本:

game.Players.PlayerAdded:Connect(function (player)
    stats = Instance.new("IntValue")
    stats.Parent = player
    stats.Name = "leaderstats"

    points = Instance.new("IntValue")
    points.Parent = stats
    points.Name = "Points"

    deaths = Instance.new("IntValue")
    deaths.Parent = stats
    deaths.Name = "Deaths"
end)

这是我作为硬币创建的部分的脚本:

script.Parent.Touched:Connect(function()
    player = game:GetService("Players").LocalPlayer
    stats = player:WaitForChild("leaderstats")
    points = stats:findFirstChild("Points")
    points.Value = points.Value + 1
    script.Parent:Destroy()

end)

当您踩在这个硬币上时,它应该将一个点添加到点列中。我试图使用 FindFirstChild 但我一直收到 NIL 异常,我无法弄清原因。我已经做了一些研究,但似乎所有我研究的东西都比我的问题更复杂。当我加载到游戏中时,排行榜确实出现了。列(Points)也出现了。有什么建议吗?

点赞
用户7572496
用户7572496

好的,有几件事情你必须改变才能让这段代码正常运行,让我来帮助你。

就像Alexander所说,你需要在变量中使用local关键字,并且给int类型的变量声明初始值。我的建议是使用Instance.new("IntValue",parent)代替换行。另外,在leaderstats中最好使用文件夹而不是值。

game.Players.PlayerAdded:Connect(function (player)
    local stats = Instance.new("Folder",player)
    stats.Name = "leaderstats"

    local points = Instance.new("IntValue",stats)
    points.Value = 0
    points.Name = "Points"

    local deaths = Instance.new("IntValue",stats)
    deaths.Value = 0
    deaths.Name = "Deaths"
end)

对于触碰部分,主要的问题在于你始终会得到nil,因为你没有接收触碰参数。你可能想将这个脚本放在服务器端,而不是在本地脚本中,并且不要使用localplayer,否则它在服务器上没有任何效果,并且没有人能够获得点数。

script.Parent.Touched:Connect(function(hit) --hit是触碰到的部分
    player = game.Players:FindFirstChild(hit.Parent.Name) --寻找该部分的父对象名称
    if player then --检测是否触碰到的是玩家
        local stats = player:WaitForChild("leaderstats")
        local points = stats:FindFirstChild("Points")
        points.Value = points.Value + 1
        script.Parent:Destroy()
    end
end)
2020-10-24 00:07:51