Apply material to all nested or non-nested instances that have the dynamic attribute "x" in the selection

Again I point you to the Learning Resources wiki lists I created …


I made a mistake in the above code sample:

    return "Dynamic Component search resulted in nil." if dcs.nil?
    return "No Dynamic Component Definitions found !" if dcs.empty?

should have used defs in the conditional expression, instead of dcs, and read as …

    return "Dynamic Component search resulted in nil." if defs.nil?
    return "No Dynamic Component Definitions found !" if defs.empty?

I have made the correction in the code above.


Here is a slightly expanded edition … it outputs the number of changed instances and returns an array of those changed instances or nil if none were changed.

module Tenquin
  extend self

  def change_mat( key, valor, mat )

    model = Sketchup.active_model
    selection = model.selection
    return "Empty Selection!" if selection.empty?

    dict  = "dynamic_attributes"

    dcs = selection.grep(Sketchup::ComponentInstance).find_all { |dc|
      dc.get_attribute(dict,key) == valor ||
      dc.definition.get_attribute(dict,key) == valor
    }
    return "No Dynamic Component Instances found !" if dcs.empty?
    puts "Instances found : #{dcs.count}"

    defs = dcs.map { |dc| dc.definition }.uniq!
    return "DC Definitions search resulted in nil." if defs.nil?
    return "No Dynamic Component Definitions found !" if defs.empty?
    puts "Definitions found : #{defs.count}"

    changed = []
    num = 0

    defs.each { |cdef|
      change = cdef.entities.grep(Sketchup::ComponentInstance)
      next if change.nil? || change.empty?
      change.each { |inst| inst.material = mat }
      num += change.size
      changed.push(*change)
    }
    
    puts "Total DC Instances material changed : #{num}"
    if num > 0
      puts "Returning an array of references to each changed instance."
      return changed
    else
      return nil
    end

  end # change_mat

end # module Tenquin