How to use functions with MotionBuilder Python

Using functions will save you from re-writing and maintaining many of the same lines of code over and over.

What is a Python Function?

“A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing. As you already know, Python gives you many built-in functions like print(), etc. but you can also create your own functions.” – Python Functions @ TutorialsPoint

How can we use a Python Function within MotionBuilder?

Functions were pretty simple to figure out, we define (“def”) the name of our function, followed by parentheses and then within those parentheses we place any parameters or arguments:

def PrintHiTake():

In the above line we have defined the name of our function and we didn’t use any parameters or arguments. Note the “:” at the end as this will be the start our code block (no different from using the “if” and “else” functions within Python).

Now let’s set up our code block to print a greet message and then the current take’s name.

def PrintHello():
    print "Hello, I'm on", FBSystem().CurrentTake.LongName

If you ran the above script little would happen, once the function is defined we then need to call it within our script.

So, lets call our function within a loop – a loop that goes through every take within your scene and prints “Hello, I’m on (insert take name here)”.

from pyfbsdk import *

for take in FBSystem().Scene.Takes:
    FBSystem().CurrentTake = take
    PrintHello() #here we are calling our function

def PrintHello():
    print "Hello, I'm on", FBSystem().CurrentTake.LongName

Now if you run that script you should get a print out (in the Python Editor’s Console window) of “Hello, I’m on (insert take name here)” for each and every take within your scene.

Try adding and removing takes and running the script again to see it update.

I hope this helps.

Leave a reply:

Your email address will not be published.

Site Footer