如何用lua在Roblox中检查对象的存在性?

我正在尝试编写一个动态分配的GUI。我有四个团队。我卡在一个特定点上。我想要一个函数,当玩家加入游戏时,检查其他团队是否已经得分以更新他们的标签。它看起来像这样:

local function updateAllLabelsLateArrival(redPoints, bluePoints, yellowPoints, greenPoints)

    game.Players.LocalPlayer.PlayerGui.ScreenGui.ReallyRedTeam.Points.Text = redPoints
    game.Players.LocalPlayer.PlayerGui.ScreenGui.ReallyBlueTeam.Points.Text = bluePoints
    game.Players.LocalPlayer.PlayerGui.ScreenGui.NewYellerTeam.Points.Text = yellowPoints
    game.Players.LocalPlayer.PlayerGui.ScreenGui.LimeGreenTeam.Points.Text = greenPoints

end

该函数是在玩家加入时从服务器端脚本远程触发的。我的问题是,并不是所有四个标签都可能存在。假设当已经有一个红队玩家在玩时,绿队球员加入,它将返回错误

ReallyBlueTeam不是ScreenGui的有效成员

我想要将每一行包装在if语句中来检查标签是否存在,就像这样:

if game.Players.LocalPlayer.PlayerGui.ScreenGui.ReallyRedTeam then game.Players.LocalPlayer.PlayerGui.ScreenGui.ReallyRedTeam.Points.Text = redPoints end

但是这会导致相同的错误。所以我的问题是,我如何检查标签是否已被创建以更新分数?谢谢

点赞
用户7242037
用户7242037

如果这是一个本地脚本,你可以使用 WaitForChild(),它将等待直到该标签被创建!

game.Players.LocalPlayer.PlayerGui:WaitForChild("ScreenGui"):WaitForChild("ReallyRedTeam"):WaitForChild("Points").Text = redPoints

关于 WaitForChild 的更多信息在这里

或者,如果你不确定它们是否被创建,你可以使用 FindFirstChild。这不会挂起。

if game.Players.LocalPlayer.PlayerGui.ScreenGui:FindFirstChild("ReallyRedTeam") then
    print("它存在")
end

关于 FindFirstChild 的更多信息在这里!希望能帮到你!

2020-01-26 18:00:53
用户5373986
用户5373986

如果你想让它们都在一行上,那么最好使用 FindFirstChild(),就像 @jjwood1600 所说的那样。我还建议使用变量来缩短你的GUI路径,正如下面所示:

local function updateAllLabelsLateArrival(redPoints, bluePoints, yellowPoints, greenPoints)

    local userGui = game.Players.LocalPlayer.PlayerGui.ScreenGui
    if userGui:FindFirstChild("ReallyRedTeam") then userGui.ReallyRedTeam.Points.Text = redPoints end
    if userGui:FindFirstChild("ReallyBlueTeam") then userGui.ReallyBlueTeam.Points.Text = bluePoints end
    if userGui:FindFirstChild("NewYellerTeam") then userGui.NewYellerTeam.Points.Text = yellowPoints end
    if userGui:FindFirstChild("LimeGreenTeam") then userGui.LimeGreenTeam.Points.Text = greenPoints end

end

在普通Lua中,你确实可以像你所做的那样使用 if 语句,不使用 FindFirstChild。但是,Roblox自己的版本RBX.Lua不支持这种方式。

2020-01-27 11:02:17