Clear Dynamic Attributes(清除动态属性)v1.0.0(转载)

插件简介:

使用此插件可清除选定对象(包括嵌套组或组件)的全部动态属性。

操作前插件会先将选中对象及其嵌套对象唯一化,然后开始清理,清理完成后,选中的对象将变为普通模型,没有任何动态组件的属性信息。

本插件由 liutao's blog 原创,本站得到授权转载,在此表示感谢。


使用教程(引用自汉化作者的网站):

操作方法

选中需要清除信息的对象 – 点击 清除动态属性 工具图标 – 等待操作完成后会提示选中项的所有动态属性已被清除。

点击工具后,如果对象比较复杂,需要等待的时间可能会比较长,请耐心等待,此时SketchUp将会是不可操作的状态,清理完成后会恢复正常。

相关代码

下方代码为清除动态属性的操作代码,不过还没有添加设为唯一,会影响到模型中复制出来的其它关联组件。

# 清除选中组或组件以及嵌套组/组件的所有 dynamic_attributes
def clear_dynamic_attributes(entity)
  # 确保当前实体有属性字典,并且包含 dynamic_attributes
  if entity.respond_to?(:attribute_dictionaries)
    dict_name = 'dynamic_attributes'
    dictionaries = entity.attribute_dictionaries

    if dictionaries && dictionaries[dict_name]
      # 获取 dynamic_attributes 字典并删除其中所有的属性
      dictionaries[dict_name].each do |key, value|
        entity.delete_attribute(dict_name, key)
      end
    end
  end

  # 如果实体是组件实例,递归清除其定义中的 dynamic_attributes
  if entity.is_a?(Sketchup::ComponentInstance)
    # 获取组件定义并检查其中的 dynamic_attributes
    component_definition = entity.definition
    clear_dynamic_attributes(component_definition)  # 清除组件定义中的动态属性
  end

  # 如果实体是组或组件,递归清除其嵌套的组/组件的动态属性
  if entity.is_a?(Sketchup::Group) || entity.is_a?(Sketchup::ComponentInstance)
    # 获取该实体的所有子实体
    entity.definition.entities.each do |sub_entity|
      clear_dynamic_attributes(sub_entity)  # 递归清除子实体的动态属性
    end
  end
end

# 使用 start_operation 和 commit_operation 来提高效率
def clear_dynamic_attributes_in_selection
  model = Sketchup.active_model
  selection = model.selection
  
  # 在一个操作中执行清除操作,避免每次操作都记录为一个单独的操作
  model.start_operation('清除动态属性', true)

  # 遍历选中的实体并清除其动态属性
  selection.each do |entity|
    clear_dynamic_attributes(entity)
  end

  # 完成操作
  model.commit_operation
  
  UI.messagebox("选中项的所有动态属性已被清除!")
end

# 执行清除操作
clear_dynamic_attributes_in_selection