【问题标题】:How to check for existence of object in Roblox with lua?如何使用 lua 检查 Roblox 中是否存在对象?
【发布时间】:2020-05-12 01:34:18
【问题描述】:

我正在尝试编写一个动态分配的 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

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

【问题讨论】:

    标签: if-statement lua label roblox


    【解决方案1】:

    假设这是一个 localcsript,你可以使用 WaitForChild() 直到标签被创建!

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

    更多关于 WaitForChild 的信息here!

    或者,如果您不确定是否会创建它们,您可以使用 FindFirstChild。这不会产生。

    if game.Players.LocalPlayer.PlayerGui.ScreenGui:FindFirstChild("ReallyRedTeam") then
        print("it exists")
    end
    

    更多关于 FindFirstChild 的信息here! 希望对您有所帮助!

    【讨论】:

    • WaitForChild 的问题是它会暂停整个脚本,直到另一个玩家加入蓝队,如果它是一个安静的服务器,这永远不会发生
    • @Taazar 如果这是在本地脚本中,则不是
    • 本地或全局脚本对其没有影响。在“ReallyRedTeam”作为“ScreenGui”的子级存在之前,红色玩家必须加入。如果红色玩家没有加入,那么您的代码将永远等待,除非您指定超时,否则永远不会进入下一行代码
    • 是的,这是个问题,因为?
    • @Corsaka 这是一个问题,因为在红色玩家加入之前,蓝色、黄色或绿色点都不会出现,因为程序无法访问显示它们的代码。 (同样在未来,请务必在 cmets 中标记您正在回复的人,否则没有通知。我只是偶然看到您的评论。)
    【解决方案2】:

    如果您希望它们都在一行中,那么最好使用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 中,您确实可以像不使用 FindFirstChild 但 Roblox 自己的版本 RBX.Lua 不使用的方式执行 if 语句。

    【讨论】:

      猜你喜欢
      • 2016-11-09
      • 2021-04-16
      • 1970-01-01
      • 2013-03-03
      • 1970-01-01
      • 2021-12-28
      • 2011-06-26
      • 2017-10-13
      • 1970-01-01
      相关资源
      最近更新 更多