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

If statement 如何用lua检查Roblox中对象的存在?,if-statement,lua,label,roblox,If Statement,Lua,Label,Roblox,我试图编写一个动态分配的gui。我有四个队。我在某一点上被卡住了。我想做一个函数,当一个玩家加入游戏时,检查其他球队是否已经得分以更新他们的标签。看起来是这样的: local function updateAllLabelsLateArrival(redPoints, bluePoints, yellowPoints, greenPoints) game.Players.LocalPlayer.PlayerGui.ScreenGui.ReallyRedTeam.Points.Text

我试图编写一个动态分配的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 is not a valid member of ScreenGui
我想用if语句包装每一行,以检查标签是否存在,如下所示:

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

但这也产生了同样的错误。所以我的问题是,如何在更新点之前检查标签是否已创建?谢谢

假设这是一个LocalCScript,您可以使用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("it exists")
end
有关FindFirstChild的更多信息!
希望有帮助

如果您希望它们都在一行中,那么最好使用@jjwood1600所说的
FindFirstChild()。我还建议使用一个变量来缩短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中,你确实可以像不使用
FindFirstChild
但Roblox自己的版本RBX.Lua那样执行if语句。

WaitForChild的问题是,它会暂停整个脚本,直到另一个玩家加入蓝队,如果是安静的话,这是永远不会发生的server@Taazar如果是这样的话就不会了在localcsriptLocal或global中,脚本对其没有影响。在“ReallyRedTeam”作为“ScreenGui”的子代存在之前,红色玩家必须加入。如果一个红色玩家没有加入,那么你的代码将永远等待,除非你指定了超时是,否则永远不会进入下一行代码,这是一个问题,因为?@Corsaka这是一个问题,因为在一个红色玩家加入之前,蓝色玩家,黄点或绿点将显示,因为程序无法访问显示它们的代码。(以后,请确保在评论中标记您回复的人,否则不会收到通知。我只是碰巧看到了您的评论。)