Python: How to Loop in Blender

thepythonconsole

AutoHotkey makes automating tasks on a computer insanely easy. But if you want to automate a task within a program, you’ve got to learn to speak that particular program’s language.

And Blender just so happens to speak Python.

Wait, what’s Blender?

It’s a 3D modeling program. A free one. Downloadable here.

Got it. What’s Python?

It’s magic. It automates tasks that would drive a normal human being insane. Say, for instance, you want a bunch of little lights to be placed at exact intervals around a little bug you modeled—Python can make that happen very quickly with loops.

The format of a Python loop looks like this:

for index in range (X):
do this

Where index is equal to the number of times the loop has run and X is the number of times you want it to loop total.

For a simple starter Python code, let’s put in 10 lights, all nice and lined up. Unfortunately you can’t just type:

for index in range (10):
make a light and be snappy about it

Blender will get all pissed and spit out an error. But if you go to the Object Operators section of the Blender API Documentation page, it’ll tell you how to refer to objects in the code and how to customize pretty much everything about them.

A quick warning. The Blender documentation looks a bit intimating at first. Well, I’ll just show you. The LAMP_ADD entry looks like this.

blender

That’s a lot of text. So I’m just gonna take the 3 most necessary pieces.

blenderedited

There are 5 types of lamps—I’m going with a point light. And I want to specify location, otherwise they’ll all get stuck in a cluster.

My 3D bug is sitting square on top of the X/Y plane. The lights need to be above his head though, so I’m setting the Z value to 4. Y can remain a constant at 0. The X value needs to go up by 1 with each loop in order to make a line, so we can use the built-in INDEX variable to keep adding 1 with each round of the loop.

Here’s the code:

loop

Plug it into the console and press ENTER twice.

loopcode
If it worked, you’ll see ten {‘FINISHED’} lines below the code and 10 lights in the scene.

finishedloop
And here’s the little bugger all lit up:

rendered

 

Advertisements
Tagged , , , , , , , ,

2 thoughts on “Python: How to Loop in Blender

  1. Very helpful! I’ve got a lot to learn from you, thanks for sharing your knowledge!

    Like

  2. Much appreciated 🙂

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: