Shihui Guo

Batch Generating and Removing Objects in Houdini

Here we write a simplest script in Houdini, to batch generating and removing objects.

First there are three ways of using python in Houdini:
- python shell
- object parameter expression
- python source editor
The major differences of these three are the previous two will load hou module by default, while the last not. However, the code you write in the python source editor will be part of the hou.session module. So if you meet the following error while you are writing your script in python source editor:

NameError: global name 'hou' is not defined

It is actually because you didn't import Houdini modules, try adding this at the beginning of your script

import hou


To add some variations to the scene, we make the box with random size and random position:

import hou
import random import randint</p>

def makeflatbox():
   num = 5
   for i in range(num):
size = randint(1, 10)
pos = randint(1, 20)
       flatbox = hou.node('/obj').createNode('geo')
       flatbox.node('file1').destroy()
       b = flatbox.createNode('box')
b.parm('sizey').set(size)
b.parm('tx').set(pos)

def removeallchild():
   children = hou.node('/obj').children()
   for child in children:
       child.destroy()</b></pre>

</code>

You can either copy and paste this code into the python source editor, or save as testBatch.py and put it into $Houdini_PATH/scripts/python/ Folder. $Houdini_Path by default will be $HIP, $HOME/houdiniX.Y ($HIH) and $HH. Then you can open your python shell and enter:

import testBatch
testBatch.makeflatbox()

Now you should be able to see 5 boxes with different lengths and positions. Call another function in the shell to delete all objects:

testBatch.removeallchild()

If you are editing your script on the fly and want to reload it frequently (surely you can close and reopen Houdini, haha, but never do that). use function reload(modulename):

reload(testBatch)

Then it will resource your script and all the changes since last resource will be effective.

Tips when you are writing in python:

Single line means expressions while multiple lines is the function body. So don't leave linebreaks inside a function

点击查看评论