Counting ComponentInstances

Is it a method that returns all of ComponentInstance included in parent ComponentInstance in all levels of nesting?

Consider
ComponentDefinition.count_instances
and
ComponentDefinition.count_used_instances [>=v2016]

I think, It gives me only number of instances, or not? I need handle to each.

ComponentDefinition.instances will give you handles to all the instances. Class: Sketchup::ComponentDefinition — SketchUp Ruby API Documentation

You asked how to count them !

But as was said:

ComponentDefinition.instances

returns an array of all of its instances, but you then need to work out the ‘parent’ of each of them in turn…

Actually, he did not. Reread the original question.

[quote=“DanRathbun, post:6, topic:28421”]
Actually, he did not. Reread the original question.
[/quote] Actually he did, reread the title:
“Counting ComponentInstances”
NOT “Collecting ComponentInstances”…
Although in the text itself I admit the OP does indeed ask for a method to ‘return’ all instances…
But given the title itself it could have meant to ‘return a count of…’ …

1 Like

I’ll give it to you, but IMO, the title is not the question, it’s the “hook”.

Gentlemen, thank you for your suggestions. Next time I’ll try to accurately describe my problems in content and topic.
But back to access to the instance. I checked ComponentDefinition.instances. It returns only instances from the first level. Do you have any ideas, suggestiosn where I should start writing method that supports these issues? How to write a loop (or something else) running through all (of all levels of nesting) instances?

thank you in advance

Marcin

Ok, I made it in this way:

def get_instance(instance)
inst_array = Array.new
instance.definition.entities.each {|inst| inst_array << [inst,1] if inst.typename == “ComponentInstance”}
until not inst_array.find {|inst| inst[1] == 1}
inst_array.each do |inst|
inst[0].definition.entities.each {|inst| inst_array << [inst,1] if inst.typename == “ComponentInstance”}
inst[1] = 0
end
end
tablica = Array.new
inst_array.each {|inst| tablica << inst[0]}
tablica
end

Do you think is there a easier way?

(1) An instance of a component cannot be inserted into it’s own definition’s entities collection. It would create a circular reference.

(2) You should check the number of used instances and bail out of the method if the count is 0.

This statement makes no sense.

ALL of a definition’s instances will be a member of it’s .instances collection.