New to ruby scripting and posting here. I have many years of amateur experience programming autolisp for CAD. I’m having some success but still befuddled with modules, classes, etc.
I would like to automatically change all materials in the model when the scene changes. The code below works when pasted into the Ruby Console, including the undo. However when I insert into the frameChange callback in scenes_v2.rb (ref below), the materials are removed instead of being replaced, and the undo breaks.
Am I dealing with modules/classes incorrectly or are you not allowed to make changes to the model during an observer call-back?
Attached is a sketchup model and my modified scenes_v2.rb code → _draftMatChanger.rb
(my added code has ### remark block ### starting line 133)
Using SU 2014 on Windows 10.
Expand for my code - works pasting into console
# credit for code comes from:
# Thomas Thomassen - tt_material_replacer\core.rb
# https://sketchucation.com/forums/viewtopic.php?f=323&t=26013
model = Sketchup.active_model
materials = model.materials
pages = model.pages
materialList = materials.map(&:name)
scenes_withMaterialOptions = []
@newmatname = "Stucco[3]"
@newmat = nil
model.materials.each{|e|@newmat=e if e.display_name==@newmatname}
@oldmatname = "Stucco[0]"
@oldmat = nil
model.materials.each{|e|@oldmat=e if e.display_name==@oldmatname}
if defined?(@newmat) and defined?(@oldmat)
model.start_operation('Replace Materials')
Sketchup.set_status_text('Replacing materials. Please wait...')
model.entities.each { |e|
if e.respond_to?(:material)
e.material = @newmat if e.material == @oldmat
end
if e.respond_to?(:back_material)
e.back_material = @newmat if e.back_material == @oldmat
end
}
model.definitions.each { |d|
next if d.image?
d.entities.each { |e|
if e.respond_to?(:material)
e.material = @newmat if e.material == @oldmat
end
if e.respond_to?(:back_material)
e.back_material = @newmat if e.back_material == @oldmat
end
}
}
Sketchup.set_status_text
model.commit_operation
end # if
Original scenes_v2.rb from this post:
https://forums.sketchup.com/t/update-to-scenes-rb-example-from-the-old-api-blog/11514
Also special thanks to DanRathbun, no way I could have gotten this far without searching & finding his many posts on coding…
_materialChanger.skp (43.6 KB)