Continuing the discussion from Question on an Animation and Counting visible copies of components:
I’m trying to display a real-time updating count of the number of instances of components, or the number of instances of related components, on the screen as a model note.
For example, if I have three distinct components, A, A#1, and B, I would like it to be able to display the instances of A and the instances of B; and to display the combined instances of A and A#1, and the instances of B.
I’ve tried my hand at writing something, but I’m only about 8 hours familiar with Ruby and using Ruby with SketchUp. I tried to clobber something together by referring to the two discussions linked above, and lots of googling. In the following code, the “General” mode does not work, and the “Strict” mode almost sort of works.
The dialog box asks for names for up to 5 components, and to choose either a general (attempts to count components and its made unique’s as one) or strict (must have exact spelling match).
Could someone help with this?
module DynamicUnitCount
def self.add_unitcount(model)
model = Sketchup.active_model
definitions = Sketchup.active_model.definitions
prompts = ["1","2","3","4","5","Type of Count:"]
defaults = ["1BED", "STUDIO","","","","General"]
list = ["","","","","","General|Strict"]
input = UI.inputbox(prompts, defaults, list, "Which components to count?")
if input
for i in 0..4
if input[i]
base_name = input[i]
note = model.add_note("component: #instances", 0.1, 0.1)
if (input[5] == "General")
general_counter = 0
definitions.each do |defn|
if defn.name.start_with? base_name
defn.add_observer(GeneralObserver.new(note, base_name, general_counter))
end
end
end
if input[5] == "Strict"
definitions.each do |defn|
if defn.name == base_name
defn.add_observer(StrictObserver.new(note, base_name))
end
end
end
end
end
end
end
class StrictObserver < Sketchup::DefinitionObserver
def initialize(entity, name)
@entity = entity
@name = name
end
def onComponentInstanceAdded(definition, instance)
count = definition.count_instances
@entity.text = "#{@name}: #{count}"
end
def onComponentInstanceRemoved(definition, instance)
count = definition.count_instances
@entity.text = "#{@name}: #{count}"
end
end
class GeneralObserver < Sketchup::DefinitionObserver
def initialize(entity, name, general_count)
@entity = entity
@count = general_count
end
def onComponentInstanceAdded(definition, instance)
count += definitions.count_intances
@entity.text = "#{@name}: #{count}"
end
def onComponentInstanceAdded(definition, instance)
count = count - definition.count_instances
@entity.text = "#{@name}: #{count}"
end
end #end class GeneralObserver
unless file_loaded?(__FILE__)
command = UI::Command.new("Unit Count"){
self.add_unitcount(Sketchup.active_model)
}
UI.menu("Plugins").add_item(command)
file_loaded(__FILE__)
end
end # module DynamicUnitCount