Return the x/y/z coordinates of a selection

Given your previous …

model = Sketchup.active_model
entities = model.entities
selection = model.selection
definitions = model.definitions

… do the following …

# Create a virtual bounding box
bbox = Geom::BoundingBox.new
# For each entity in the selection array, ...
#  add to it the bounding box of each entity
selection.each { |ent| bbox.add(ent.bounds) rescue nil }
# Get the bottom front left corner as a Geom::Point3d
origin = bbox.corner(0)
# Use Ruby's multiple assignment
x, y, z = origin.to_a

# Add the instance
inst = entities.add_instance(definitions[0],[x+12,y,z])

# Set it selected
selection.clear
selection.add(inst)

REF:


As an aside … why did I use a rescue nil modifier within the each iterator block ?

(Cliick to expand answer ...)

Because I seem to remember in some SketchUp versions there being some strange object references held within either the selection or entities collections. So in the event that any of the entity items in the selection do not respond to a bounds method call, and a NoMethodError is raised, the rescue nil modifier will return nil for that iteration (which does nothing as the each iterator itself simply ignores the return values of the block’s iterative evaluations, and when done just returns the collection object itself, … in this case the selection.)

1 Like