How to get root node in MEL Script?

panofish picture panofish · Mar 17, 2014 · Viewed 7.5k times · Source

I have come across an existing piece of code that does this, but I assume there must be a better way. So, I need to get a highest level in mesh node in Autodesk Maya.

// List all mesh objects
string $nodess[] = `ls -type mesh` ;

// Replace existing items on active list with this
select -r $nodess[0] ;   

int $i = 1 ;

while ($i < 30) {
    // Pick up the tree 30 times
    pickWalk -d up ;
    $i++ ;
}

// List all selected objects
string $rootNode[] = `ls -sl` ;

// Clear selection
select -cl ;

string $myroot = $rootNode[0] ;

Answer

theodox picture theodox · Mar 17, 2014

to get the root, just string-split the long name:

global proc string get_root(string $node)
{
    string $longname[] = ls("-l", $node);
    string $tokens[];
    tokenize($longname[0], "|", $tokens);
    return $tokens[0];
}

Of course it's much more elegant in Python:

root = cmds.ls(node, l=True)[0].split("|")[0]

You could also re-write the orignal function by calling listRelatives -p until it returns nothing; but the string method is easier