Di Wang
Di Wang

Reputation: 481

Maya Python: how to reference a file and immediately select a child from that referenced file

I need write a python script for automation, I need to do following:

For example: The structure of the reference file is like this:

My attempt was this:

import maya.cmds as cmds

cmds.file("M:/.../rig.ma", r=True, ignoreVersion = True, namespace = "Rig")

Above codes reference the rig file, my Question is: How to select control_grp, immediately after the rig file is imported.

Upvotes: 2

Views: 8692

Answers (1)

theodox
theodox

Reputation: 12208

Most of the time the reference file contents will come in as part of a namespace (identified with a name and a colon at the front of the names, eg 'reference:pCube1`. If you are controlling the namespace when you reference the file in you will be able to search inside the namespace instead of creating the sets -- but, depending on how you or your user has set the options in the reference dialog you may not know the namespace ahead of time.

if you have the namespace, it's easy:

rig_namespace = "rig" # or whatever you call it
control_grp = "control_grp")  # name of the object you want
cmds.select(rig_namespace + ":" + control_grp)

If you are not sure what namespace to search you can save the contents of the scene before the reference is loaded into a python set() and then make a new set() out of the contents after the reference comes in. Using the set difference() function you can subtract the pre-load set from the post-load set, giving you all of the things which came in with the referenced file. You can then uses cmds.select to grab the items you're looking for out of the file.

Getting the imported file contents

import maya.cmds as cmds
before = set(cmds.ls(type='transform'))
cmds.file(r"path/to/file.ma", reference=True)
after = set(cmds.ls(type='transform'))
imported = after - before
print imported 

getting a control rig out of the imported file

controls = set(cmds.ls("*control_grp*", type = transform)) # wildcards in 
case maya has added numbers or prefixes
imported_controls = controls & imported # this gets only controls just added
cmds.select(*imported_controls) # you need the asterisk to unpack the set

Upvotes: 2

Related Questions