【问题标题】:Is there simpler way of finding objects within parent objects on Roblox (Lua)是否有更简单的方法在 Roblox (Lua) 上的父对象中查找对象
【发布时间】:2021-12-28 23:00:01
【问题描述】:
local colorwheel = script.Parent
local clickdetector = colorwheel.ClickDetector

--- Left mouse click (turn on)
clickdetector.MouseClick:connect(function()
   print("lights on")
   for _,p in pairs(workspace.OceanVillagedr201:GetChildren()) do
      if p.Name == ("Downstairs") then
         for _,x in pairs(p:GetChildren()) do
             if x.Name == "Kitchen Bar Counter" then
                 for _,d in pairs(x:GetChildren()) do
                     if d.Name == "barlight" then
                         for _,j in pairs(d:GetChildren()) do
                             if j.Name == "light" then
                                 j.Transparency = 0
                             else
                             end
                         end
                     end
                 end
             end
         end
      end
   end
end)


--- Right mouse click (turn off)
clickdetector.RightMouseClick:connect(function()
  print("lights off")
  for _,p in pairs(workspace.OceanVillagedr201:GetChildren()) do
     if p.Name == "Downstairs" then
         for _,x in pairs(p:GetChildren()) do
             if x.Name == "Kitchen Bar Counter" then
                 for _,d in pairs(x:GetChildren()) do
                     if d.Name == "barlight" then
                         for _,j in pairs(d:GetChildren()) do
                             if j.Name == "light" then
                                 j.Transparency = 1
                             else
                             end
                         end
                     end
                 end
             end
         end
     end
  end
end)

此脚本负责在“色轮”检测到点击时打开和关闭灯。为了保持我的工作空间井井有条,我将模型放入模型中,然后将这些模型放入文件夹中,本质上为我要修改的原始对象创建了很多 .parents。如您所见,这导致我不得不调用 :GetChildren() 函数,因此我可以让脚本在所有 parents 中搜索单个对象。有没有办法简化这一点,或者这是否被认为是在 Roblox 上编写脚本的适当方式?

【问题讨论】:

    标签: lua roblox


    【解决方案1】:

    您可以像在表上查找属性一样为模型的子级建立索引。您可以将点运算符用于名称中没有空格的子项,或方括号用于名称中的子项。

    您可以像这样访问已知路径的子级:

    local village = workspace.OceanVillagedr201
    local light = village.Downstairs["Kitchen Bar Counter"].barlight.light
    light.Transparency = 0
    

    请注意,如果您在任何名称中犯了错误,或者任何对象尚未加载,则此方法将引发错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-12
      • 2017-06-15
      • 1970-01-01
      • 2023-03-21
      • 1970-01-01
      • 2021-03-24
      • 2018-09-24
      • 2019-04-26
      相关资源
      最近更新 更多