Community
Maya Programming
Welcome to Autodesk’s Maya Forums. Share your knowledge, ask questions, and explore popular Maya SDK topics.
cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

Unparent, do stuff then reparent

2 REPLIES 2
SOLVED
Reply
Message 1 of 3
Anonymous
3309 Views, 2 Replies

Unparent, do stuff then reparent

I want to unparent an object (and make it a child of the world), do some things, and then reparent it to its original parent transform.

Here's what I'm trying:

 

import maya.cmds as cmds

sel = cmds.ls(selection=True)[0]
initialParent = cmds.listRelatives(sel, parent=1)[0]
cmds.parent(sel, world=True)

#Do stuff

cmds.parent(sel, initialParent)

The hierarchy is

group1

> cube1 (selected when running script)

 

The error says: 'No object matches name: group1|cube1

 

It must be my fundamental misunderstanding of how python works - I'm assuming initialParent is getting changed when cube1 is unparented? And therefore it no longer works? I'm a bit baffled.

 

Any help much appreciated!

2 REPLIES 2
Message 2 of 3
zewt
in reply to: Anonymous

This is a really common problem with using cmds/MEL.  The node path can contain some of the parents, which is done to disambiguate the name if you have multiple nodes with the same name.  When you unparent the node, that name is no longer valid.  This is really hard to work around with that API, and can cause a lot of subtle bugs.

 

The solution is to use PyMEL instead of cmds.  It holds proper references to objects, so things don't break if you reparent or rename nodes.  For the most part its API matches cmds, so you can just replace cmds with it:

 

 

import pymel.core as pm
sel = pm.ls(selection=True)[0] initialParent = pm.listRelatives(sel, parent=1)[0] pm.parent(sel, world=True) pm.parent(sel, initialParent)

 

I left that as-is so you can see that it works without many changes, but with PyMEL I'd actually do this:

 

 

sel = pm.ls(selection=True)[0]
initialParent = sel.getParent()
sel.setParent(world=True)    
sel.setParent(initialParent)

There are some cases where you need to fall back on cmds, since for some uses PyMEL has performance issues, but I always recommend using PyMEL by default.

 

 

Message 3 of 3
Anonymous
in reply to: zewt

That's super useful info, and thanks for the extra script 🙂 !

Can't find what you're looking for? Ask the community or share your knowledge.

Post to forums  

Autodesk Design & Make Report