Thread: Python to MEL
View Single Post
# 2 21-11-2015 , 03:59 AM
NextDesign's Avatar
Technical Director
Join Date: Feb 2004
Posts: 2,988
Try:

Code:
select "removeKids_*";

string $transforms[] = `ls -sl -transforms`;

for ($x = 0; $x < size($transforms); $x++)
{
    string $children[] = `listRelatives $transforms[$x]`;
    
    for ($i = 0; $i < size($children) - 1; $i++)
    {
        delete $children[$i + 1];
    }
}
You can also simplify your python code to:
Code:
import maya.cmds as cmds

transforms = cmds.ls("removeKids_*", sl=True, type="transform")

for x in xrange(len(transforms)):
    children = cmds.listRelatives(transforms[x], type="transform")
    if children: cmds.delete(children)
Which removes the nested loop, as well as the extra selection call.

Notice that I changed the variable name from "meshes" to "transforms", as this is the type of object that you are storing. I also modified the call to listRelatives to only return transform nodes. This stops the program from deleting objects of any other type (such as the parent object's shape node). I also switched range to xrange, as it doesn't store all numbers from 0 to len(transforms) - 1 in memory at once. Instead it generates a single number per iteration, which reduces memory usage. I also added the if statement, even though it wouldn't fail without it, it would throw a warning stating that no object was to be deleted if there were no child transform nodes under the parent.


Imagination is more important than knowledge.

Last edited by NextDesign; 21-11-2015 at 04:22 AM.