Skip to content

Instantly share code, notes, and snippets.

@Onefabis
Last active April 10, 2019 20:41
Show Gist options
  • Save Onefabis/0c3e2b9192ec5384df15433c8a04bf41 to your computer and use it in GitHub Desktop.
Save Onefabis/0c3e2b9192ec5384df15433c8a04bf41 to your computer and use it in GitHub Desktop.
Quickly add selected objects into empty group for every selected object
import re
import maya.cmds as mc
def addToGroup( *args ):
post,replacePost,postIndex,dupIgnore = parseArgs( args )
allObj = mc.ls( sl=1, l=1 )
rootNode = [ a.rsplit('|',a.count('|')-1 )[0] if a.count('|') > 1 else a for a in allObj ]
newHi = sum( ( [ k for k in mc.listRelatives( m, ad=1, typ='transform', f=1 ) ] + [m] if mc.listRelatives( m, ad=1, typ='transform', f=1 ) else [m] for m in list( set( rootNode ) ) ), [] )
hiSel = [ x for x in newHi if x in allObj ]
newNObjects = []
for a in hiSel:
parentObj = mc.listRelatives( a, p=1, f=1 )
lookName = a.rsplit('|',1)[-1]
if '_' + post not in lookName:
lookName += '_' + post
nums = re.findall(r'\d+', lookName)
if postIndex <= len(nums) and postIndex:
splt = re.split(r'(\d+)', lookName)
count = int(splt[postIndex*2-1])
splt[postIndex*2-1] = '%s'
newName = ''.join(splt)
else:
newName = lookName + '%s'
count = 0
while mc.objExists( newName % str(count) ):
count += 1
if parentObj:
grp = mc.duplicate( po=1, n=newName % str(count) )[0]
newObject = a.replace( parentObj[0], parentObj[0] + '|' + grp )
else:
grp = mc.duplicate( po=1, n=newName % str(count) )[0]
newObject = grp + a
mc.parent( a, grp)
replacedNewNObjects = [ x.replace( a, newObject ) if a in x else x for x in newNObjects ]
newNObjects = replacedNewNObjects
newNObjects.append( newObject )
mc.select( newNObjects, r=1 )
def parseArgs( args ):
post = ''
replacePost = ''
postIndex = 0
dupIgnore = 1
stringArgs = [ x for x in args if isinstance(x, basestring)]
intArgs = [ x for x in args if type(x)==int ]
if stringArgs:
post = stringArgs.pop(0)
if stringArgs:
replacePost = stringArgs.pop(0)
if intArgs:
postIndex = intArgs.pop(0)
if intArgs:
dupIgnore = intArgs.pop(0)
return post,replacePost,postIndex,dupIgnore
# Add postfix in quotes if you need
addToGroup( 'GRP',1 )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment