July 15, 2010

SketchUp Ruby API 1 : create a plugin

In this article I am going to show you how to create small plugins for Google Sketchup using the Google SketchUp Ruby API. I will cover the very basics here to give a starting point for the beginners.

The plugin is in fact a ruby script so the first thing we need is a text editor, anything that can edit text will do the job but using a ruby editor or IDE is easier because it gives you features like syntax coloring, completion, etc. In case you wonder I will use TextMate. Open you favorite text editor and create a new file called hello_world.rb in the Google Sketchup plugins directory :

  • Mac OS X : /Library/Application Support/Google SketchUp [n]/plugins
  • Windows : c:\Program Files\Google\Google SketchUp [n]\Plugins

Your file need to load a ruby library that contains all the classes and methods to interact with SketchUp.

# First we pull in the standard API hooks.
require 'sketchup'

The first line starts with the sharp character (#) that is used for comments, everything is ignored from this character to the end of the line. The second line load the SketchUp API definitions.

As usual we will start with a basic hello world add the following line to your code

# First we pull in the standard API hooks.
require 'sketchup'

UI.messagebox("Hello world")

Just launch SketchUp and you should see your Hello World. Well that's great but we might want to have a little control over our plugin and run it only when we need it. A way to do this is to add an item in one of the menu of the menu bar and launch our program when we click on it. We can't add menus so we have to choose a existing one, but there is a Plugin menu that may not be displayed if there is nothing inside. Let's add a "Hello world" item to the plugin menu.

# First we pull in the standard API hooks.
require 'sketchup'

UI.menu("Plugins").add_item("My plugin") {
  UI.messagebox("Hello world")
}

All the methods that manipulate the graphical user interface are in the module "UI". The first thing we need is the retrieve the menu called "Plugins" that is the job of the menu method, it return a menu object corresponding to the given name. The menu object offers a method to add items in that menu called add_item. We want our menu item to display "My plugin" so we give that string as the first parameter of add_item. The second parameter is a procedure represented by all the lines of code between the opening and closing braces. This procedure will automaticaly be called by SketchUp when we click on the item. So we just add our line to display a message box with hello world in it.

We are done, this was quite simple but we have good bases to start the real things. We know how to display message to the user and add menu items to launch our script when the user click on it.