Duncan
Duncan

Reputation: 1

changing part of an object name in maya python

I feel like this should be easy but all of my searching has been in vain.

I'm in maya, I have a series of objects who's names end with _LOC i want to run a python script that renames them to end with _JNT instead. I managed to get it to work on a single object, but my for loop just does the first object and then stops. Here's what i have so far:

import maya.cmds as mc

sel=mc.ls(selection=True)

for each in sel:
    item=sel[0]
    newname=item.split('_')
    mc.rename(newname[0]+'_JNT')

Upvotes: 0

Views: 7305

Answers (3)

beisbeis
beisbeis

Reputation: 148

Others have correctly addressed the error in your code.

Maya also has a built-in tool to do this, under Modify -> Search and Replace Names. It does exactly what your code is doing. It also has the ability to replace all names in a scene, or just your selection.

Upvotes: 0

haggi krey
haggi krey

Reputation: 1978

Since maya.cmds work with strings the same way mel does, the script can fail if you rename the parent of a child node because the full name of the child changes in Maya but not in the selection list. It depends a lot on your setup.

I recommend to use pymel instead because it relies on MObjects and not on strings:

import pymel.core as pm

sel=pm.ls(selection=True)

for each in sel:
    newname=each.nodeName().replace("_LOC", "_JNT")
    each.rename(newname)

Upvotes: 1

theodox
theodox

Reputation: 12218

You're not actually using your loop. You just need to use the loop variable each where you're currently referencing the selection:

import maya.cmds as mc

sel=mc.ls(selection=True)

for each in sel:
    newname=each.split('_')
    mc.rename(newname[0]+'_JNT')

Upvotes: 2

Related Questions