Introduction to Python Scripting in Maya – Part 1: Creating and Manipulating Objects



in this series we'll introduce the basics of Python scripting in Maya in part 1 we'll look at how to create and modify scene objects in part 2 we'll cover how to work with the users current selection in part three we'll delve into keyframed animations in part four we'll explore how to create a simple user interface and in part five we'll see how we can generate expressions along with custom attributes in this part we'll cover how to use Python to create randomly distributed instances of the same object in the scene the main tool we'll be using is the script editor which you can open by clicking on the following button you can also embed the script editor in a layout by right-clicking on a layout icon when you manipulate Maya's interface for example to create a cube in the scene the script editor will echo the triggered Malcolm and in this case the Mel command to create a cube is polycube accompanied by several flags to invoke this command in python select the Python tab and type import Maya CMDs as CMDs the as keyword lets us write CMD s instead of Maya CMDs this module provides most of the Mel commands to Python to see which commands are available select help Python command reference your web browser should open to an alphabetically sorted command list search for polycube when our cube was created the echoed polycube mel command was given the following flags according to the Python reference the CH flag enables construction history note that the on and off key words in mell translate to the true and false key words in Python the O or object flag creates the object in the scene when it's false the cube will still be created but will only exist as a mesh object in the dependency graph by default this flag is set to true which should suit our purposes the WH and D flags respectively indicate the values for the width height and depth of the cube finally the CUV flag stands for create UVs the default value of four avoids texture distortion to directly translate the Malcolm and into Python type the following line note that each flag is paired with its value using the equal sign in fact the CH o and c UV Flags are all set to their default values so we can remove them to produce the same effect to customize the name of this cube add the name flag and set it to my cube with a trailing pound symbol Maya will replace this pound character to ensure that the cubes name is unique delete the cube in the scene then highlight the script and press execute a new cube is created in the scene run the following print statement to see what Maya returned in the result variable the STR function converts the variables contents into plain text in the output pane we can see that the result variable actually points to a list of two items lists in Python are delimited by square brackets each item is separated by a comma the first item my cube 1 is the name of the cubes transform node the second item polycube 1 is the name of the cubes underlying polygon data structure the lowercase u indicates that the string is encoded in the Unicode text format to understand what my cube 1 and polycube 1 refer to note that the Maya scene is organized as a graph which is often referred to as the dag short for directed acyclic graph our cube is represented in this graph by a combination of a transform node and a shape node to get a clearer intuition about this relationship open the outliner select display shapes and expand my cube 1 my cube 1 is a transform node which determines where in space the cube exists this includes its translation rotation and scale the shape node defines the display and tessellation properties of its input object polycube 1 the polycube 1 object contains the polygons actual data structures including its vertices edges faces and UV s now that we've got a more comprehensive grasp of the polycube commands result we can look at how to create several instances of our cube to do this manually select the cube and select edit duplicate special option box set the geometry type to instance and press apply a new cube is created in the scene at the same position as the first one let's move it away from the first cube expand both transform nodes in the outliner notice that the my cube to transform node has the same shape node as the first cube changing the geometry will therefore affect all the instances in the resulting male output notice that the instance command was used let's look at how to add this command to our Python script first type the following lines at the beginning of our script to get rid of all the existing cubes in the scene this will make testing easier since we won't have to manually delete all the cubes before running our script every time the LS command returns object names which fulfill a specific requirement in this case we want to fetch all the objects whose name starts with my cube the star is a wildcard character which matches any text after the my cube prefix such as my cube 1 and so on this if statement checks whether or not the LS command has returned anything by checking the length of the cube list with the Len function the delete command then removes each item in the cube list from the scene the instance command takes a transform node as an input set the transform name variable to the first item contained in the result list in other words my cube 1 note that the first item in a Python list is indexed at 0 right the following lines to create an instance of the cube and print the result you the original cube and the instance cube are created in the same position so let's use the Move command to reposition the second cube over by 10 units along the x-axis so far we could have done all of this quite easily by hand but what if we wanted to create 50 instances with random positions rotations and scales to do this we'll need to place our instancing code inside a for loop this range causes the for loop to iterate 50 times and increases the value of i from 0 to 49 while we're at it let's comment out our print statements since we won't need to print each result every time an object is created use the pound character to comment a single line out we'll also change the width height and depth of our original cube to one to minimize any overlaps it's worth noting that consistent indentation is crucial in python in our script each level of indentation is equivalent to 4 spaces instead of moving each cube by 10 units away from the original we'll use the value of I as the y-coordinate to stack the instanced cubes when we run the script the cubes are effectively stacked one on top of the other let's look at randomizing the position of each cube import pythons random module type random seed 1 2 3 4 to use the same random number sequence every time we run our script you can change 1 2 3 4 to any other number to get a different result sample a value between negative 10 and 10 for the x-coordinate sample value between 0 and 20 for the y-coordinate and sample a value between negative 10 and 10 for the Z coordinate use each of these values in the Move command the cubes are now randomly scattered above the grid to rotate the cubes randomly and to scale them we'll use the same technique sample three values between 0 and 360 for the x y and z axes of rotation use the rotate command to rotate each instance sample a single value between 0.3 and 1.5 to randomize the scaling factor use the scale command to scale each instance if we open the outliner now we'll notice that all the cubes are placed at the top level the last step is to group them neatly together use the group command to create an empty group above the for loop the name flag uses the transform name of our original cube call the parent command to add each instance to the group below the for loop call the hide command on the original cube to make it invisible in the scene this visibility change will not affect the instances once they're created as a final step use the xform command on the instance group with the center pivots flag is set to true to centre its pivot when we run the script our instances are now neatly grouped under the my cube one instance group we can now comment out our cleanup code using paired Triplets of single quotation marks as we progress through this series we'll be accumulating a few Python tabs in our script editor so to easily identify which script we're working on add the name of the script as a comment on the top line let's call this script random cubes py save it under Maya's scripts subdirectory under your documents you can also save it to your shelf as cubes in the next part we'll cover how to work with the users current selection to create aimed constraints you

28 Replies to “Introduction to Python Scripting in Maya – Part 1: Creating and Manipulating Objects”

  1. I prefer a tutorial where i do exercices, i write code, then i understand them after writing them, here you explain everything and i think i dont need to understand this when im starting learning python scripting

  2. This series looks great. My #1 wish is for a step by step guide on how to setup a custom IDE as coding inside Maya is not really ideal. Code completion and tons of other IDE tools are not in the Maya Script editor. Pycharm or VisualStudio Code IDE setup would be great!

  3. import maya.cmds as cmds

    result = cmds.polyCube(w=4.9277,h=2.927,d=4.740,name='mypolycube#')

    print'result:' +str(result);
    // Error: result = cmds.polyCube(w=4.9277,h=2.927,d=4.740,name='mypolycube#')
    //
    // Error: Line 3.8: Syntax error //

  4. I work in Animation and Film and I find your material PERFECT! I've been wanting to learn, but books etc have not been proper motivation, you're really fast-tracking me in combination with other basic python tutorials. Thank you so much, this deserves to be endorsed by Autodesk and I'm happy the resources have been getting better in recent years. I'm not a robot, at least not in metallic form, thank you.

  5. When the Python tab is selected, Maya should print in Python instead of MEL. We shouldn't have to do the error-prone busywork of translating by hand from MEL to Python.

  6. Hi, thanks for your video! and I have a question, I learnt c and c++ but have no experience with python, will I be able to follow alone? or should I learn python before I jump into maya script?

  7. Hi, thanks for the nice Video.
    Until 7:30 all went right but when i want to run the script, Maya says there is an invalid syntax in line 1. But im sure I can´t do everything wrong at the 1st line.

  8. Hi firstly thanks this is my first bit of coding and you've done it superbly. Only one thing I am having trouble understanding. In your for loop you have – for i in range(0, 50): what is the i? I replaced it with instanceResult which seemed to make more sense to me and it worked which is fine but I'd like to just understand what you did there please.

  9. Hey! I'm currently taking Digital Graphics and Animation. See, we're working in Maya for a lot of our projects. I recently was given a room to work on and in my room I was told to create a baby grand piano. I was wondering if you could help me with that. I thought that using this could help me in this project. But see whenever I get to the part where you finish the myCube name and delete the cube, "//Error: Line 3.8: Syntax error"

  10. Hello! Thank you for this great tutorial.
    I need to merge around 200 cubes together but the Union feature can be used with only two polygons at a time. I tried using the command: cmds.nurbsBoolean( 'nurbsCube1', 'nurbsCube2', nsf=1, op=0 ) but I can't seem to figure out how to script that in python in a 'for' loop since the name of the polygons changes each time. I would really appreciate your help with this.

Leave a Reply

Your email address will not be published. Required fields are marked *