Create nested component from entities

So I’m trying to create a component in a component from it’s entities. Like in these screenshots
1
2

This is how I try to do it:

selection = Sketchup.active_model.selection
component = selection[0]
entities = component.definition.entities

definitions = Sketchup.active_model.definitions
new_definition = definitions.add('new_definition')
new_definition.add_instance(entities, Geom::Transformation.new) # undefined method `add_instance' for ComponentDefinition

comp = Sketchup.active_model.entities.add_instance(new_definition, Geom::Transformation.new)

But I get an error on row 7 “Undefined method `add_instance’ for ComponentDefinition”.
Is there a better way of solving my problem?
I’m using Sketchup2022.

That’s because an ComponentInstance is an Entity that is added to an Entities collection, as in your final code line, not to a ComponentDefinition. So, you would need to add the entities to the Entities collection of new_definition, not to new_definition itself.

Of course, this all begs the question of why you are trying to build a nested component in one that contains nothing else. A shell of nesting that contains only one object is a waste! What is the ultimate objective?

It’s a weird I know.

This is how I added the Entities to the new_definition. But I feel like I did it wrong?

3

selection = Sketchup.active_model.selection
component = selection[0]
entities = component.definition.entities
group = Sketchup.active_model.entities.add_group

entities.each do |entity|
  if entity.is_a?(Sketchup::Face)
    group.entities.add_face(entity.vertices.map {|v| v.position.to_a })
  elsif entity.is_a?(Sketchup::Edge)
    start = entity.start.position.to_a
    end_ = entity.end.position.to_a
    group.entities.add_line([start, end_])
  end
end

definitions = Sketchup.active_model.definitions
new_definition = definitions.add('new_definition_name')
new_definition.entities.add_group(group)

comp = Sketchup.active_model.entities.add_instance(new_definition, Geom::Transformation.new)

What about this…

model = Sketchup.active_model
newComponent = model.entities.add_group(model.selection).to_component
1 Like

Nice thanks, that seems to be what I’m looking for.

1 Like