How to trigger a event when I draw a rectangle face with ruby api

During a drawing rectangle procedure, can a event be triggered?
Thus we can add other codes in the event to meet with our requirement.

For that I would use an entities observer.

From the docs.
Note:

The methods of this observer fire in such a way that making changes to the model while inside of them is dangerous.

class MyEntitiesObserver < Sketchup::EntitiesObserver

  def onElementAdded(entities, entity)
    #this event fires every time an entity is added.
    #we are only interested in events when the rectangle tool is active and a face is being added.
    #note that the event also fires as each of the edges for the rectangle are added.
    puts 'added rectangle' if Sketchup.active_model.tools.active_tool_name && entity.is_a?(Sketchup::Face)
  end
end

# Attach the observer
Sketchup.active_model.entities.add_observer(MyEntitiesObserver.new)

… also, this observer callback may fire multiple times, once for the face and once each for the face’s edges.

That’s what I said. :slight_smile:

1 Like

Neil,

Many thanks ! Can the observer only be defined for a typical scene or operation in a project, not for a whole project, for the drawing procedures may be used by onther operations.

Yes you can add and remove the observer as needed.

@my_observer  = MyEntitiesObserver.new
Sketchup.active_model.entities.add_observer(@my_observer)

#do stuff that needs to observe when a rectangle is added...

#turn the observer 'off' again.
Sketchup.active_model.entities.remove_observer(@my_observer)
1 Like