# Insert object on mouse click

**URL:** <https://forums.sketchup.com/t/insert-object-on-mouse-click/102381>\
**Category:** Ruby API\
**Created:** [September 4, 2019, 11:03pm UTC](https://forums.sketchup.com/t/insert-object-on-mouse-click/102381 "2019-09-04T23:03:35Z")\
**Posts on this page:** 16\
**Page:** 1

<div class="post-metadata">

**Author:** ![Beppe64](https://avatars.discourse-cdn.com/v4/letter/b/e99b99/32.png) [@Beppe64](https://forums.sketchup.com/u/Beppe64)\
**Post date:** [September 4, 2019, 11:03pm UTC](https://forums.sketchup.com/t/insert-object-on-mouse-click/102381/1 "2019-09-04T23:03:35Z")

</div>

Hello everyone, I wrote a small file Api Ruby, with which I create a pillar, setting the two  
measurements at the base of the pillar, side along the x-axis and y and the height, all by entering the measurements  
inputbox… in creating the face for the “pushpull”, the first point equals pt1 [0, 0, 0]  
origin of the X, Y, Z axes … I would like the pillar object to remain momentarily attached  
cursor and subsequently inserted on screen at a precise point at the click of the mouse insertion,  
I hope I have explained myself… Possibly? What should I write to the Ruby file, for this insertion wait  
pillar object… Thank you.

Greetings

Joseph

[https://global.discourse-cdn.com/sketchup/original/3X/d/7/d764e59c584d6ab18f5ba10934b62fb53af6cafe.mp4](https://global.discourse-cdn.com/sketchup/original/3X/d/7/d764e59c584d6ab18f5ba10934b62fb53af6cafe.mp4)

[Pil\_1\_piano.rb](https://forums.sketchup.com/uploads/short-url/7ljtUNmoZzc6pIbihb0tsfVfjlT.rb) (1.1 KB)

---

<div class="post-metadata">

**Author:** ![tt\_su](https://sea2.discourse-cdn.com/sketchup/user_avatar/forums.sketchup.com/tt_su/32/17_2.png) [@tt\_su](https://forums.sketchup.com/u/tt_su)\
**Post date:** [September 5, 2019, 8:32am UTC](https://forums.sketchup.com/t/insert-object-on-mouse-click/102381/2 "2019-09-05T08:32:01Z")

</div>

You can use `model.place_component` for that:

> **[Class: Sketchup::Model](https://ruby.sketchup.com/Sketchup/Model.html#place_component-instance_method)**
>
> This is the interface to a SketchUp model.

---

<div class="post-metadata">

**Author:** ![Beppe64](https://avatars.discourse-cdn.com/v4/letter/b/e99b99/32.png) [@Beppe64](https://forums.sketchup.com/u/Beppe64)\
**Post date:** [September 5, 2019, 9:17am UTC](https://forums.sketchup.com/t/insert-object-on-mouse-click/102381/3 "2019-09-05T09:17:46Z")

</div>

Thanks for the answer, I’ve already tried watching " model.place.component",  
but I understood very little, if he was kind enough to show me with practical example  
using my ruby file, it would be great…Thank you

Joseph

---

<div class="post-metadata">

**Author:** ![TIG](https://sea2.discourse-cdn.com/sketchup/user_avatar/forums.sketchup.com/tig/32/198_2.png) [@TIG](https://forums.sketchup.com/u/TIG)\
**Post date:** [September 5, 2019, 11:28am UTC](https://forums.sketchup.com/t/insert-object-on-mouse-click/102381/4 "2019-09-05T11:28:44Z")

</div>

Currently your code adds a group and then creates geometry in it.

You could add a new definition into the model’s definitions, and then add your geometry into its entities context, much as you did with the group.entities.  
[Class: Sketchup::DefinitionList — SketchUp Ruby API Documentation](http://ruby.sketchup.com/Sketchup/DefinitionList.html#add-instance_method)  
[Class: Sketchup::ComponentDefinition — SketchUp Ruby API Documentation](http://ruby.sketchup.com/Sketchup/ComponentDefinition.html#entities-instance_method)

Then use **model.place\_component(…)** with the reference to this new component definition.

* * *
Also note that you should wrap your method inside your own module, so that it remains separate from everyone elses...

---

<div class="post-metadata">

**Author:** ![Beppe64](https://avatars.discourse-cdn.com/v4/letter/b/e99b99/32.png) [@Beppe64](https://forums.sketchup.com/u/Beppe64)\
**Post date:** [September 5, 2019, 12:33pm UTC](https://forums.sketchup.com/t/insert-object-on-mouse-click/102381/5 "2019-09-05T12:33:25Z")

</div>

I understand very little…Thanks all the same

Joseph.

---

<div class="post-metadata">

**Author:** ![felipe.de.abreu.prazeres](https://avatars.discourse-cdn.com/v4/letter/f/ce7236/32.png) [@felipe.de.abreu.prazeres](https://forums.sketchup.com/u/felipe.de.abreu.prazeres)\
**Post date:** [November 18, 2019, 2:31pm UTC](https://forums.sketchup.com/t/insert-object-on-mouse-click/102381/6 "2019-11-18T14:31:41Z")

</div>

Greetings Thomas. I feel like a fan talking to my idol here. 😀  
Small follow up question to place\_component method.  
It returns **Sketchup::Model** instead of the **ComponentInstance**. Seems reasonable since _repeat_ argument could be set to _true_ and it would return something like an _array_ OR _ComponentInstance_.

Therefore, how would you grab a handle to the **ComponentInstance** (assuming _repeat_ set to _false_).  
Should I go with **Sketchup.active\_model.entities[-1]** or is there something more intuitive.

Thanks, Felipe.

---

<div class="post-metadata">

**Author:** ![DanRathbun](https://sea2.discourse-cdn.com/sketchup/user_avatar/forums.sketchup.com/danrathbun/32/500_2.png) [@DanRathbun](https://forums.sketchup.com/u/DanRathbun)\
**Post date:** [November 18, 2019, 3:54pm UTC](https://forums.sketchup.com/t/insert-object-on-mouse-click/102381/7 "2019-11-18T15:54:55Z")

</div>

There are several ways.

`1.` Since you must have a reference to the component definition, you can take an array snapshot of it’s **instances** collection before and then subtract it from the array afterward.

```ruby
before = cdef.instances
model.place_component(cdef,false)
# Wait some time because place_component returns immediately.
new_instances = cdef.instances - before

```

> [@felipe.de.abreu.prazeres](#):
>
> Small follow up question to place\_component method.  
> It returns **Sketchup::Model** instead of the **ComponentInstance**. Seems reasonable since _repeat_ argument could be set to _true_ and it would return something like an _array_ OR _ComponentInstance_ .

But the main problem is knowing **when** the placing has been completed (as `place_component` is non-blocking and returns immediately.)

This is the reason why it just returns the model object - ie the method call returns immediately and does not wait for the user to place any instances.

Changing how it works now is not possible. But adding a sister method that does wait and retrun an array of placed instances is an option.

* * *

A better approach is likely to use a temporary definition observer …

```ruby
module Author::SomePlugin
  # inside your plugin module ...
  extend self

  def onComponentInstanceAdded(definition, instance)
    @instance = instance
    definition.remove_observer(self)
  end

  def place_component(definition)
    @instance = nil
    # Set up a timer to check for the new instance and remove observer
    # if the timeout is reached (ie, user canceled the placement.)
    @timeout = 10.0
    @elapsed = 0
    @tid = UI.start_timer(1.0,true) do
      @elapsed += 1.0
      if @instance
        UI.stop_timer(@tid)
        respond_to_instance(@instance)
      elsif @elapsed > @timeout
        UI.stop_timer(@tid)
        definition.remove_observer(self)
      end
    end
    # Attach this module as temporary observer:
    definition.add_observer(self)
    # Place the instance with the MoveTool:
    definition.model.place_component(definition,false)
  end

  def respond_to_instance()
    # Do something with @instance
  end

end # plugin module

```

You might also watch the toolstack. The PlaceComponent tool will change to the MoveTool at some point.

* * *

There are a bunch of open API Issues regarding placing components with the API(s) …

- [Model#load\_and\_place\_component](https://github.com/SketchUp/api-issue-tracker/issues/6)

- [place\_component block form callback](https://github.com/SketchUp/api-issue-tracker/issues/279)

- [Allow a Sketchup::Model#import :transform option](https://github.com/SketchUp/api-issue-tracker/issues/271)

- [Add a #most\_recent (or #last) method to some SketchUp collections](https://github.com/SketchUp/api-issue-tracker/issues/272)

---

<div class="post-metadata">

**Author:** ![felipe.de.abreu.prazeres](https://avatars.discourse-cdn.com/v4/letter/f/ce7236/32.png) [@felipe.de.abreu.prazeres](https://forums.sketchup.com/u/felipe.de.abreu.prazeres)\
**Post date:** [November 19, 2019, 8:48pm UTC](https://forums.sketchup.com/t/insert-object-on-mouse-click/102381/8 "2019-11-19T20:48:21Z")

</div>

Perfect. It is working like a charm using the sister method. Thanks. Appreciate it.

> [@DanRathbun](#):
>
> This is the reason why it just returns the model object - ie the method call returns immediately and does not wait for the user to place any instances.

Makes perfect sense for me now. And once again thanks for going further and explaining the main reason behind it returns Sketchup::Model.

---

<div class="post-metadata">

**Author:** ![DanRathbun](https://sea2.discourse-cdn.com/sketchup/user_avatar/forums.sketchup.com/danrathbun/32/500_2.png) [@DanRathbun](https://forums.sketchup.com/u/DanRathbun)\
**Post date:** [November 19, 2019, 9:25pm UTC](https://forums.sketchup.com/t/insert-object-on-mouse-click/102381/9 "2019-11-19T21:25:14Z")

</div>

sister method?

---

<div class="post-metadata">

**Author:** ![SHAWO](https://sea2.discourse-cdn.com/sketchup/user_avatar/forums.sketchup.com/shawo/32/127893_2.png) [@SHAWO](https://forums.sketchup.com/u/SHAWO)\
**Post date:** [October 21, 2021, 1:04pm UTC](https://forums.sketchup.com/t/insert-object-on-mouse-click/102381/10 "2021-10-21T13:04:13Z")

</div>

Thks dan,i’m also troubled by this question，I try a test.rb  
as the code

```auto
$mod = Sketchup.active_model # 
$ent = $mod.entities # 
#sel = mod.selection # 

#

class Creatgz
 
  def onLButtonDown flags,x,y,view
    ip1 = Sketchup::InputPoint.new
    ip1.pick view,x,y
    @ip = ip1.position
    crt_wrb
  end
  
  def crt_wrb

prompts = ["high", "wight", "depth"] #
defaults = ["2400mm","800mm","600mm"]
yjgz = UI.inputbox(prompts, defaults, "test")

h = yjgz[0] #
w = yjgz[1] #
d = yjgz[2] 

h = h.to_i.mm
w = w.to_i.mm
d = d.to_i.mm

@wrb = [] #

#
box1 = $ent.add_face [0,0,0],[w,0,0],[w,d,0],[0,d,0]
box1.pushpull -h
box1_group = $ent.add_group box1.all_connected
lb = box1_group.to_component

@wrb << Sketchup.active_model.active_entities[-1] #

box2 = $ent.add_face [w*2,0,0],[w*3,0,0],[w*3,d,0],[w*2,d,0]
box2.pushpull -h
box2_group = $ent.add_group box2.all_connected
rb = box2_group.to_component

@wrb << Sketchup.active_model.active_entities[-1] #

wrb_newname = Sketchup.active_model.entities.add_group (@wrb) #

wrb_newname = wrb_newname.to_component #

  $ent.transform_entities @ip,wrb_newname

   end

end

cm1 = UI::Command.new("test-box"){
Sketchup.active_model.select_tool Creatgz.new
}

toolbar = UI::Toolbar.new"test-box"
toolbar.add_item cm1
toolbar.show

```

how can I put the component when my code create the test-box at the point I want to,and it can be catch the mid-point or endpoint. at the same time, we can see the icon like this ![无标题](https://global.discourse-cdn.com/sketchup/original/3X/d/0/d0ec7c78991a77df5323524c5915d2a90368fa8f.png)  
I have searched many examples of similar problems in the forum，but there’s no completed code。can u help me finish the code then i can understand the methods to put components.Thks again！

---

<div class="post-metadata">

**Author:** ![DanRathbun](https://sea2.discourse-cdn.com/sketchup/user_avatar/forums.sketchup.com/danrathbun/32/500_2.png) [@DanRathbun](https://forums.sketchup.com/u/DanRathbun)\
**Post date:** [October 21, 2021, 1:36pm UTC](https://forums.sketchup.com/t/insert-object-on-mouse-click/102381/12 "2021-10-21T13:36:49Z")

</div>

> [@SHAWO](#):
>
> I have searched many examples of similar problems in the forum，but there’s no completed code。

Refer to the official examples repository.

> **[GitHub - SketchUp/sketchup-ruby-api-tutorials: SketchUp Ruby API Tutorials...](https://github.com/SketchUp/sketchup-ruby-api-tutorials)**
>
> SketchUp Ruby API Tutorials and Examples. Contribute to SketchUp/sketchup-ruby-api-tutorials development by creating an account on GitHub.

* * *

@SHAWO I’ve looked at your code a bit and it is **off-topic**.

It is not inserting a component instance using a tool, and should have been in it’s **own topic** rather than reviving this topic after **2 years**.

All this said, I previously posted a complete example Instance DragTool here …

[Draw model while moving mouse in custom tool - #11 by DanRathbun](https://forums.sketchup.com/t/draw-model-while-moving-mouse-in-custom-tool/59637/11)

---

<div class="post-metadata">

**Author:** ![DanRathbun](https://sea2.discourse-cdn.com/sketchup/user_avatar/forums.sketchup.com/danrathbun/32/500_2.png) [@DanRathbun](https://forums.sketchup.com/u/DanRathbun)\
**Post date:** [October 21, 2021, 3:11pm UTC](https://forums.sketchup.com/t/insert-object-on-mouse-click/102381/13 "2021-10-21T15:11:46Z")

</div>

Note that the forums is not usually the place for “completed code”.  
(I myself have posted a smattering of complete code examples here, but intend to move them to GitHub gists or full code repositories.)

I did post a complete example Instance Drag Tool here …

[Draw model while moving mouse in custom tool - #11 by DanRathbun](https://forums.sketchup.com/t/draw-model-while-moving-mouse-in-custom-tool/59637/11)

* * *

> **Please learn Ruby best practices for a shared environment. ( ...click to expand... )**
>
> Regarding your “test” code. Please learn Ruby best practices for a shared environment.  
> **No global variables.**
> 
> A unique namespace module wrapping everything (but even a name like “Testing” for namespace sake is fine for posting snippets.)  
> A namespace module is important because it is a no-no to define classes at the top level for your own use. (Only Ruby Core and API classes that everyone will use should be defined in the top level ObjectSpace.)
> 
> Within **your** top level namespace module is where you define extension submodules. This is important because each extension’s code needs to be separated from each other so that they do not interfere.
> 
> Define custom classes inside extension submodules where they will be used.
> 
> When coding use good practice so that when you need help others are able to understand what your code is trying to do:
> 
> - Comment your classes and methods with **at least** a simple description. This lets other readers know what a class or method is intended to do. And later when you yourself come back to the code months later, these comments will help you remember how things work.
> 
> - Insert comments in between code statements when more explanation is needed.
> 
> - Use **descriptive** reference (variable) names, except for the simplest iterator index variables in loops.
> 
> - Use proper 2 space indentation. (Set your code editor to replace tabs with spaces so that when you need to post code snippets the forum can display the code correctly.)

~

---

<div class="post-metadata">

**Author:** ![SHAWO](https://sea2.discourse-cdn.com/sketchup/user_avatar/forums.sketchup.com/shawo/32/127893_2.png) [@SHAWO](https://forums.sketchup.com/u/SHAWO)\
**Post date:** [October 23, 2021, 12:36pm UTC](https://forums.sketchup.com/t/insert-object-on-mouse-click/102381/14 "2021-10-23T12:36:50Z")

</div>

Thank a lot,Dan!  
I have solved the problem ，i find the answer in official examples with writing notes myself。  
As a beginner without coding experience, i think it’s too bad that there’s no notes in official examples’ code,many people can’t understand every method in code and why coding like this.people should search the API document and try to guess the way for complete codes。  
Cos English is not my mother language，it’s too slow to learn skp develop。  
fortunately，Dan help many beginner persevere in his study^\_^

---

<div class="post-metadata">

**Author:** ![DanRathbun](https://sea2.discourse-cdn.com/sketchup/user_avatar/forums.sketchup.com/danrathbun/32/500_2.png) [@DanRathbun](https://forums.sketchup.com/u/DanRathbun)\
**Post date:** [October 23, 2021, 1:30pm UTC](https://forums.sketchup.com/t/insert-object-on-mouse-click/102381/15 "2021-10-23T13:30:42Z")

</div>

> [@SHAWO](#):
>
> As a beginner without coding experience, i think it’s too bad that there’s no notes in official examples’ code,

The **examples** editions have no comments, but if they have a **tutorials** edition then that **will** have comments.

> [@SHAWO](#):
>
> people should search the API document and try to guess the way for complete codes

The API documentation is a concise dictionary of API objects, not a teaching tool.

I created lists of resources for learning Ruby …

> [@Ruby Learning Resources \[WikiLists\]](https://forums.sketchup.com/t/ruby-learning-resources-wikilists/22861/):
>
> All seven of the lists below are set as wikis. card_index INDEX [notebook PRIMERS & GUIDES](http://forums.sketchup.com/t/ruby-learning-resources/22861/2)[books BOOKS](http://forums.sketchup.com/t/ruby-learning-resources/22861/3)[mortar_board TUTORIALS](http://forums.sketchup.com/t/ruby-learning-resources/22861/4)[card_box REFERENCE](http://forums.sketchup.com/t/ruby-learning-resources/22861/5)[clipboard TEMPLATES](http://forums.sketchup.com/t/ruby-learning-resources/22861/6)[newspaper NEWS](http://forums.sketchup.com/t/ruby-learning-resources/22861/7)[bulb IDEAS](http://forums.sketchup.com/t/ruby-learning-resources/22861/8)

---

<div class="post-metadata">

**Author:** ![tt\_su](https://sea2.discourse-cdn.com/sketchup/user_avatar/forums.sketchup.com/tt_su/32/17_2.png) [@tt\_su](https://forums.sketchup.com/u/tt_su)\
**Post date:** [October 25, 2021, 12:05pm UTC](https://forums.sketchup.com/t/insert-object-on-mouse-click/102381/16 "2021-10-25T12:05:35Z")

</div>

> [@SHAWO](#):
>
> As a beginner without coding experience, i think it’s too bad that there’s no notes in official examples’ code,many people can’t understand every method in code and why coding like this.people should search the API document and try to guess the way for complete codes。

Have a look in the `tutorials` folder: [https://github.com/SketchUp/sketchup-ruby-api-tutorials/tree/main/tutorials](https://github.com/SketchUp/sketchup-ruby-api-tutorials/tree/main/tutorials)

These examples are heavily commented:

> <https://github.com/SketchUp/sketchup-ruby-api-tutorials/blob/main/tutorials/01_hello_cube/tut_hello_cube.rb>

> <https://github.com/SketchUp/sketchup-ruby-api-tutorials/blob/main/tutorials/01_hello_cube/tut_hello_cube/main.rb>

---

<div class="post-metadata">

**Author:** ![SHAWO](https://sea2.discourse-cdn.com/sketchup/user_avatar/forums.sketchup.com/shawo/32/127893_2.png) [@SHAWO](https://forums.sketchup.com/u/SHAWO)\
**Post date:** [October 26, 2021, 1:27am UTC](https://forums.sketchup.com/t/insert-object-on-mouse-click/102381/17 "2021-10-26T01:27:03Z")

</div>

Thank you so much！TT
