You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Roblox Lua如何查找blocks文件夹下Selected属性为true的子对象

实现思路与代码示例

核心逻辑

  • 首先获取blocks文件夹实例,优先用WaitForChild避免加载时序问题导致找不到对象
  • 遍历文件夹下的目标子对象:用GetChildren()仅遍历一级子对象,用GetDescendants()遍历所有嵌套层级的子对象
  • 对每个子对象调用GetAttribute("Selected")判断:返回值严格等于true的就是符合要求的对象

可直接使用的代码示例

-- 获取Workspace下的blocks文件夹
local Workspace = game:GetService("Workspace")
local blocksFolder = Workspace:WaitForChild("blocks")
-- 存储符合条件的对象
local selectedBlocks = {}

-- 情况1:仅查找blocks文件夹的一级子对象
for _, child in blocksFolder:GetChildren() do
    if child:GetAttribute("Selected") == true then
        table.insert(selectedBlocks, child)
    end
end

-- 情况2:需要查找blocks文件夹下所有嵌套层级的子对象,取消注释即可使用
-- for _, child in blocksFolder:GetDescendants() do
--     if child:GetAttribute("Selected") == true then
--         table.insert(selectedBlocks, child)
--     end
-- end

-- 测试输出符合条件的对象名称
for _, block in selectedBlocks do
    print("选中的方块:" .. block.Name)
end

注意事项

  • 判断时必须用== true严格匹配,避免属性不存在返回nil时的逻辑误判
  • 如果你的自定义属性是用布尔值类型的实例成员而非Attribute实现的,可把GetAttribute("Selected")替换为child:FindFirstChild("Selected"),同时判断其Value属性是否为true即可

内容的提问来源于stack exchange,提问作者twanman1412

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 10:48:04