SketchUp Ruby API - 删除所有图层时的ArgumentError

时间:2016-09-12 13:42:24

标签: ruby sketchup

我制作了一个脚本来删除从.dwg文件导入的所有图层:

# import the dwg file
show_summary = false
if Sketchup.active_model.import file_path, show_summary

    # delete all layer
    protected_layers = ['Layer0', '! 3D', '! AutoCad']
    10.times do
        Sketchup.active_model.definitions.purge_unused
        Sketchup.active_model.layers.purge_unused

        Sketchup.active_model.layers.each { |layer|
            layer_name = layer.name
            if not layer.deleted? and not protected_layers.include? layer_name  
                puts "\tdeleted"
                Sketchup.active_model.layers.remove layer
            end
        }
    end
end

当我导入一个大的dwg文件时,所有图层都不会立即导入(或多或少100层)...所以我添加了一个10.times循环到所有图层被完全删除。我的脚本完美运行,直到剩下10层。我收到这样的错误:

Error: #<ArgumentError: layer doesn't belong to this model>

那么如何检查我的图层还没有被删除?我尝试了这些解决方案,但似乎没有人工作

  • layer.deleted?不返回true
  • layers.at layer.name不返回nil
  • begin;rescue;end围绕循环崩溃 Sketchup

2 个答案:

答案 0 :(得分:1)

您正在迭代要从中删除元素的集合。这绝不是一件安全的事情。

将图层缓存到一个迭代的数组。

以下是一个例子:

model = Sketchup.active_model
# Map layer names to layers - as object comparison is much faster than string
# comparisons.
protected_layers = ['Layer0', '! 3D', '! AutoCad'].map { |layer_name|
  model.layers[layer_name]
}
# Start an operation as this keeps the undo stack clean and makes the script
# fun faster.
model.start_operation('Remove Layers', true)
model.layers.to_a.each { |layer|
  next if layer.deleted? || protected_layers.include?(layer)
  model.layers.remove(layer)
}
model.commit_operation

答案 1 :(得分:0)

我创建了一个Sketchup.active_model.layers[l.name].nil?解决方案,以防止已删除图层。这是我的解决方案的样本

layers.take_while{|l| not l.deleted? and not layers[l.name].nil? }.each { |layer|
    puts layer.name
    unless protected_layers.include? layer.name  
        puts "\t[*] deleted"
        layers.remove layer
    else
        puts "\t[ ] undeleted"
    end
}