有没有简单的方法在Roblox (Lua)的父对象中查找对象?

local colorwheel = script.Parent
local clickdetector = colorwheel.ClickDetector

--- 左键点击(打开)
clickdetector.MouseClick:connect(function()
   print("灯开了")
   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)

--- 右键点击(关闭)
clickdetector.RightMouseClick:connect(function()
  print("灯关了")
  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)

这个脚本负责在“colorwheel”检测到点击时打开和关闭灯。为了保持我的工作区有组织性,我将模型放入模型中,然后将这些模型放入文件夹中,从而基本上创建了很多原始对象的_.parents_。您可以看到,这导致我必须调用_:GetChildren()_函数,以便脚本可以搜索所有_parents_以寻找单个对象。是否有简化此过程的方法,或者这是否被视为在Roblox上编写脚本的适当方式?

原文链接 https://stackoverflow.com/questions/70013332

点赞
stackoverflow用户2860267
stackoverflow用户2860267

您可以像查找表属性一样索引模型的子元素。对于名字中没有空格的子元素,您可以使用点运算符,对于有空格的子元素,您可以使用方括号。

您可以像以下方式访问已知路径的子元素:

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

请注意,如果任何一个名称有误或任何一个对象尚未加载,这种方法将抛出错误。

2021-11-18 01:21:53